I'm new to Grails so forgive my ignorance--if other info is helpful I'll do my best to get it posted.
I've created a single domain model class ToolKitComponent that is defined as:
class ToolKitComponent {
String componentName
String componentVersion
int componentDownloads
Date compnentLastUpdate
static constraints = {
}
}
I have a controller that I just want to test the ORM by persisting an example, so here's the contents of the controller:
def index() {
ToolKitComponent i = new ToolKitComponent()
i.setComponentName("TestComponent")
i.setComponentVersion("v1.10")
i.setComponentDownloads(1)
i.setCompnentLastUpdate(new Date())
i.save()
}
I've installed the MySql database plugin and updated my DataSource.groovy to:
dataSource {
pooled = true
driverClassName = "com.mysql.jdbc.Driver"
dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
loggingSql = true
}
// other settings
environments {
development {
dataSource {
String dbCreate = "create"
String url = "jdbc:mysql://localhost/testDataBase"
String username = "myUser"
String password = "myPass"
}
}
}
I've created the database testDataBase and granted all to the username.
When I run the application, I get:
Hibernate: insert into tool_kit_component (version, compnent_last_update, component_downloads, component_name, component_version) values (?, ?, ?, ?, ?)
| Error 2012-07-11 20:01:52,727 [http-bio-8080-exec-2] ERROR util.JDBCExceptionReporter - Table "TOOL_KIT_COMPONENT" not found; SQL statement:
insert into tool_kit_component (version, compnent_last_update, component_downloads, component_name, component_version) values (?, ?, ?, ?, ?) [42102-164]
| Error 2012-07-11 20:01:52,752 [http-bio-8080-exec-2] ERROR errors.GrailsExceptionResolver - JdbcSQLException occurred when processing request: [GET] /TestProject/
Table "TOOL_KIT_COMPONENT" not found; SQL statement:
insert into tool_kit_component (version, compnent_last_update, component_downloads, component_name, component_version) values (?, ?, ?, ?, ?) [42102-164]. Stacktrace follows:
Message: Table "TOOL_KIT_COMPONENT" not found; SQL statement:
insert into tool_kit_component (version, compnent_last_update, component_downloads, component_name, component_version) values (?, ?, ?, ?, ?) [42102-164]
Line | Method
->> 329 | getJdbcSQLException in org.h2.message.DbException
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 169 | get in ''
| 146 | get . . . . . . . . in ''
| 4753 | readTableOrView in org.h2.command.Parser
| 4731 | readTableOrView . . in ''
| 954 | parseInsert in ''
| 375 | parsePrepared . . . in ''
| 279 | parse in ''
| 251 | parse . . . . . . . in ''
| 217 | prepareCommand in ''
| 415 | prepareLocal . . . in org.h2.engine.Session
| 364 | prepareCommand in ''
| 1121 | prepareCommand . . in org.h2.jdbc.JdbcConnection
| 71 | <init> in org.h2.jdbc.JdbcPreparedStatement
| 267 | prepareStatement . in org.h2.jdbc.JdbcConnection
| 1051 | prepareStatement in ''
| 508 | prepareStatement . in org.apache.commons.dbcp.DelegatingConnection
| 400 | prepareStatement in org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper
| 11 | index . . . . . . . in TestProject.HomeController
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run . . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run in java.lang.Thread
I'm using Grails 2.0.4.
Any help is appreciated!
Take away the String in your datasource definition
environments {
development {
dataSource {
dbCreate = "create"
url = "jdbc:mysql://localhost/testDataBase"
username = "myUser"
password = "myPass"
}
}
}
Related
More beginner problems for me with Groovy/Grails.
Groovy version 2.4.8 Grails version 2.5.1
I have tried multiple ways to serialize an instance of one of my domain classes or an ArrayList of instances of that domain class.
When trying to serialize a single instance I get a stack overflow error.
The code and stack trace is shown below
def getAdvisors(String keystrokes, String firm) {
def advisors = priceBlotterService.advisorsForKeystrokes(keystrokes, "", 30)
def a1 = advisors[0]
def json = JsonOutput.toJson(a1)
}
Caused by InvocationTargetException: null
->> 198 | doFilter in grails.plugin.cache.web.filter.PageFragmentCachingFilter
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 63 | doFilter in grails.plugin.cache.web.filter.AbstractFilter
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run . . . in java.lang.Thread
Caused by StackOverflowError: null
->> 100 | invoke in org.codehaus.groovy.reflection.CachedMethod
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 62 | getProperty in groovy.lang.MetaBeanProperty
| 42 | getValue in groovy.lang.PropertyValue
| 388 | getProperties in org.codehaus.groovy.runtime.DefaultGroovyMethods
| 290 | writeObject in groovy.json.JsonOutput
| 329 | writeArray in ''
| 286 | writeObject in ''
| 424 | writeMap in ''
| 294 | writeObject in ''
| 329 | writeArray in ''
| 286 | writeObject in ''
| 424 | writeMap in ''
Advisor, Case, and Firm Classes:
class Advisor {
String firstName
String lastName
String fullName
String city
String state
Firm firm
static belongsTo = [Case, Firm]
static hasMany = [cases:Case]
static constraints = {
}
}
class Case {
String caseCode
String internalComment
String externalComment
Date dateCreated
String createdBy
Date dateUpdated
String updatedBy
static belongsTo = [owner:User, caseStatusType:CaseStatusType]
static hasMany = [advisor:Advisor]
static mapping = {
dateCreated sqlType: "date"
dateUpdated sqlType: "date"
}
static constraints = {
dateCreated(nullabe: false)
dateUpdated(nullable: false)
}
}
class Firm {
String name
static constraints = {
}
}
Edit:
I found a fundamental problem with my domain class/table that could have something to do with this and needs to be resolved.
I try to do a simple get from the user table and I get an error message indicating there is no id field. Having a hard time figuring out what is going on. Some details are below.
line of code
User[] users = User.findAll()
error message
org.springframework.jdbc.BadSqlGrammarException: Hibernate operation: could not extract ResultSet; bad SQL grammar [n/a]; nested exception is org.postgresql.util.PSQLException: ERROR: column this_.id does not exist Position: 8
User class
class User {
String firstName
String lastName
static constraints = {
}
}
ddl for user table
CREATE TABLE "user"
(
id BIGINT DEFAULT nextval('user_id_seq'::regclass) PRIMARY KEY NOT NULL,
first_name VARCHAR(30),
last_name VARCHAR(30),
version BIGINT
);
CREATE UNIQUE INDEX user_id_uindex ON "user" (id);
Edit:
Fixed issuer with User table/class. User is a keyword in Postresql so I just refactored to EndUser.
I suspect there is some issue with the data structure you have, which is causing the JSON builder to go into an infinite loop.
You may want to review this for info on issues with dates: https://issues.apache.org/jira/browse/GROOVY-7682
This may work instead:
import grails.converters.JSON
def json = new JSON(a1)
I can't find this documented anywhere, but don't use JsonOutput for domain objects.
I just ran into a similar issue. DomainObject instances have this "neat" property called all which will return every instance of the domain object.
When JsonOutput tries to serialize your object, it uses DefaultGroovyMethods.getProperties, which includes the all property. This means that your code will cause hibernate to load EVERY copy of your Advisor class into memory.
In my case I ran out of memory. My system got stuck in garbage collection loops.
In your case, when your a1 class is being rendered, it is including the 'all' property, which is the full list of all Advisors. Each Advisor also has an "all" property so it tries to render every advisor. And so on. Eventually giving you your stack overflow.
I have a Grails 2.4.5 GSP page which loads two iFrame:
<iframe scrolling="no"
src="${createLink(controller:'admin', action:'page1', id: serviceCard.id)}"></iframe>
<iframe scrolling="no"
src="${createLink(controller:'admin', action:'page2', id: serviceCard.id)}"></iframe>
After every second reload or so I have the following problem. Note that this does not occur all the time.
On my GSP I see Error 500. The console shows the following error:
2015-08-01 21:41:11,530 [http-nio-8080-exec-3] ERROR errors.GrailsExceptionResolver - ConcurrentModificationException occurred when processing request: [GET] /test/adminServiceCard/previewCard/4b6dc4730fd3acd80a
Stacktrace follows:
Message: Error processing GroovyPageView: Error executing tag <asset:stylesheet>: null
Line | Method
->> 527 | doFilter in /grails-app/views/adminServiceCard/previewCard.gsp
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Caused by GrailsTagException: Error executing tag <asset:stylesheet>: null
->> 6 | doCall in /grails-app/views/adminServiceCard/previewCard.gsp
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Caused by ConcurrentModificationException: null
->> 1456 | sort in java.util.ArrayList
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 175 | sort in java.util.Collections
| 145 | fileNameWithoutExtensionFromArtefact in asset.pipeline.AssetHelper
| 99 | loadRequiresForTree in asset.pipeline.DirectiveProcessor
| 76 | getFlattenedRequireList in ''
| 83 | getDependencyList in asset.pipeline.AssetPipeline
| 79 | doCall . . . . . in asset.pipeline.grails.AssetsTagLib$_closure2
| 6 | doCall in Users_mg_Documents_Grails_GGTS3_6_3_test_grails_app_views_adminServiceCard_previewCard_gsp$_run_closure1
| 10 | run . . . . . . in Users_mg_Documents_Grails_GGTS3_6_3_test_grails_app_views_adminServiceCard_previewCard_gsp
| 198 | doFilter in grails.plugin.cache.web.filter.PageFragmentCachingFilter
| 63 | doFilter . . . . in grails.plugin.cache.web.filter.AbstractFilter
| 53 | doFilter in grails.plugin.springsecurity.web.filter.GrailsAnonymousAuthenticationFilter
| 62 | doFilter . . . . in grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter
| 46 | doFilterInternal in org.grails.jaxrs.web.JaxrsFilter
| 1142 | runWorker . . . in java.util.concurrent.ThreadPoolExecutor
| 617 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run . . . . . . in java.lang.Thread
Edit: Here is the content of adminServiceCardpreview_gsp.groovy.gsp:
import org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin
import org.codehaus.groovy.grails.web.pages.GroovyPage
import org.codehaus.groovy.grails.web.taglib.*
import org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException
import org.springframework.web.util.*
import grails.util.GrailsUtil
class gsp_majestella_adminServiceCardpreview_gsp extends GroovyPage {
public String getGroovyPageFileName() { "/WEB-INF/grails-app/views/adminServiceCard/preview.gsp" }
public Object run() {
Writer out = getOut()
Writer expressionOut = getExpressionOut()
registerSitemeshPreprocessMode()
printHtmlPart(0)
createTagBody(1, {->
printHtmlPart(1)
invokeTag('javascript','g',5,['library':("jquery"),'plugin':("jquery")],-1)
printHtmlPart(1)
invokeTag('stylesheet','asset',7,['src':("perfect-scrollbar/perfect-scrollbar.min.css")],-1)
printHtmlPart(2)
invokeTag('javascript','asset',8,['src':("perfect-scrollbar/perfect-scrollbar.jquery.min.js")],-1)
printHtmlPart(2)
invokeTag('javascript','asset',9,['src':("jquery.cycle.all.js")],-1)
printHtmlPart(1)
invokeTag('stylesheet','asset',11,['src':("preview.css")],-1)
printHtmlPart(3)
})
invokeTag('captureHead','sitemesh',13,[:],1)
printHtmlPart(4)
createTagBody(1, {->
printHtmlPart(5)
if(true && (showCard == true)) {
printHtmlPart(6)
if(true && (serviceCard.imageItems)) {
printHtmlPart(7)
expressionOut.print(createLink(controller:'image', action:'getImage', id:serviceCard.imageItems[0].id, absolute:true))
printHtmlPart(8)
}
printHtmlPart(9)
expressionOut.print(serviceCard?.title)
printHtmlPart(10)
expressionOut.print(serviceCard?.company?.name)
printHtmlPart(11)
}
printHtmlPart(12)
if(true && (showDetail == true)) {
printHtmlPart(13)
loop:{
int i = 0
for( imageItem in (serviceCard.imageItems) ) {
printHtmlPart(14)
expressionOut.print(createLink(controller:'image', action:'getImage', id:imageItem.id, absolute:true))
printHtmlPart(15)
i++
}
}
printHtmlPart(16)
expressionOut.print(raw(serviceCard.description))
printHtmlPart(17)
}
printHtmlPart(18)
})
invokeTag('captureBody','sitemesh',116,[:],1)
printHtmlPart(19)
}
public static final Map JSP_TAGS = new HashMap()
protected void init() {
this.jspTags = JSP_TAGS
}
public static final String CONTENT_TYPE = 'text/html;charset=UTF-8'
public static final long LAST_MODIFIED = 1438521220000L
public static final String EXPRESSION_CODEC = 'html'
public static final String STATIC_CODEC = 'none'
public static final String OUT_CODEC = 'none'
public static final String TAGLIB_CODEC = 'none'
}
How can I solve this problem?
This error looks a lot like this one from asset pipeline.
You should remove all //=require in previewCard.gsp and then work through which is causing the error.
I am having troubles with using the findOrCreateBy method in the Bootstrap.groovy.
class Guest {
String firstname
String lastname
Gender gender
static constraints = {
firstname blank: false
lastname blank: false
gender nullable: false
}
}
enum Gender {
MALE('male'), FEMALE('female')
final String v
Gender(String s) { v = s }
}
And in the Bootstrap I try to create Guests if they do not exist yet.
Guest guest = Guest.findOrCreateByFirstnameAndLastnameAndGender(firstname, lastname, Gender.MALE)
guest.save()
The first time I run the app against MySQL everything works fine. The apps starts without any error. If I run the app a second time (this time with guest in the database) I get the following failure.
| Error 2013-11-17 14:27:37,621 [localhost-startStop-1] ERROR context.GrailsContextLoader - Error initializing the application: Unknown name value [1] for enum class [ch.silviowangler.ch.cisposiamo.Gender]
Message: Unknown name value [1] for enum class [ch.silviowangler.ch.cisposiamo.Gender]
Line | Method
->> 105 | methodMissing in org.grails.datastore.gorm.GormStaticApi
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 106 | createGuest in BootStrap
| 102 | createGuest . . . . . . . . . . in ''
| 66 | doCall in BootStrap$_closure1
| 308 | evaluateEnvironmentSpecificBlock in grails.util.Environment
| 301 | executeForEnvironment in ''
| 277 | executeForCurrentEnvironment . . in ''
| 262 | run in java.util.concurrent.FutureTask
| 1145 | runWorker . . . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 744 | run . . . . . . . . . . . . . . in java.lang.Thread
It seems the the first time Gorm writes values '0' and '1' to the database. In the second run it fails to convert these 0 and 1 into the corresponding enum value. Can anybody tell me what I am doing wrong?
Try this - Add the parameter generateSimpleParameterMetadata=true to your url connect string,
...
url = "jdbc:mysql://localhost/bootstraptest?generateSimpleParameterMetadata=true"
...
This has something to do with the way the driver interprets the enum meta data (frankly i don't understand it well) see http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html
This solution is very db specific, so you don't need any other changes
Note that the actual enum label will now be stored in the database ('NEW', 'WIP', 'DONE' instead of 0, 1, 2)
I think this is related to mysql, I dont have mysql to test it against and never worked with mysql, but try to specifically map the enum, like this:
static mapping = {
...
gender column: 'gender', sqlType: 'enum', name: 'gender'
}
ref
And if you are manually creating your database table , try to create the enum for your columns similar to this:
CREATE TABLE sizes (
name ENUM('small', 'medium', 'large')
);
ref
This is another article that can help here
I suggest to change mapping using IdentityEnumType:
static mapping = {
...
gender column: 'gender', type: IdentityEnumType
}
Modify your Enum, by adding id to it:
public enum Gender {
MALE (1, "male"),
FEMALE (2, "female"),
final Integer id
final String value
Gender (Integer id, String value) {
this.id = id
this.value = value
}
String getValue() {
return value
}
String toString() {
return name()
}
String getKey() {
return name()
}
That should help you.
I'm using Codeigniter V2.1.3 and I have a calendar template that have a scheduling stuff and I want to count the events in a particular date. Here is my database:
----Table: schedule -----
id | materialID | borrowerID | date_reserve |
------------------------------------------------
1 | 7 | 7 | 2013-08-16 |
2 | 10 | 10 | 2013-08-16 |
1 | 12 | 13 | 2013-08-18 |
What I want is in my calendar template the total event for the date=2013-08-16 will be 2 events. Here is my code which is not working coz it keeps on sending me only 1 event maybe you could figure out where is my mistake in here:
$query = $this->db->select('*')->from('schedule')->like('date_reserve', "$year-$month")->get();
$cal_data = array();
foreach ($query->result() as $row) {
$index = ltrim(substr($row->date_reserve,8,2), '0');
$cal_data[$index] = count($row->borrowerID). 'event(s)';
}
return $cal_data;
Any help?
If you want number of events for exact date: YYYY-MM-DD you can replace like with where:
$r = $this->db->select('id, materialID, borrowerID, date_reserve')
->where('date_reverse', $year."-".$month."-".$day)
->get('schedule')
->result();
Also you can print_r the result so you will see what the result is. Also you can echo last query: echo $this->db->last_query();
Edit:
We had to run query per each date to fetch the number of events.
$cal_data = array();
for($i=1;$i<=31;$i++)
{
$this->db->select('COUNT(id) as count,date_reserve,borrowerID');
$this->db->from('schedule');
$this->db->where('date_reserve',"$year-$month-$i");
//$this->db->group_by('date_reserve');
$query = $this->db->get();
foreach ($query->result() as $row) {
$cal_data[$index] = $row->count. 'event(s)';
}
try using group_by
public function get_results($date) {
$this->db->select('COUNT(id),date_reserve');
$this->db->from('schedule');
$this->db->like('date_reserve',$date);
$this->group_by('date_reserve');
$result = $this->db->get();
return $result->result_array();
}
Now I have a really strange problem which I'm unable to understand.
I've got hibernate properly configured. I can load data from my mysql database without any problems. But I'm not able to insert data. Here is my hibernate.cfg.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/bookmaker</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="javax.persistence.validation.mode">none</property>
<mapping class="de.wettprofi.objects.Bookmaker"/>
<mapping class="de.wettprofi.objects.Match"/>
<mapping class="de.wettprofi.objects.LogEntry"/>
</session-factory>
</hibernate-configuration>
It's about the class LogEntry. Here is some code that should persit the object into the database:
public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
BufferedReader reader = request.getReader();
String json = reader.readLine();
try {
LogEntry log_entry = null;
if (json != null && !json.isEmpty()) {
log_entry = new LogEntry();
JSONParser parser = new JSONParser();
JSONObject json_dict = (JSONObject) parser.parse( json );
//initalize proper LogEntry object
}
if( log_entry != null ) {
Session session = get_hibernate_session();
System.out.println("Logging of LogEntry into the database\n" + log_entry.toString() );
session.save( log_entry );
session.flush();
System.out.println("Logging DONE");
}
} catch( Exception e ) {
e.printStackTrace();
}
}
public Session get_hibernate_session()
{
//Opening a hibernate session
SessionFactory sessionFactory = null;
try {
Configuration hibConfiguration = new Configuration().addResource("hibernate.cfg.xml").configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(hibConfiguration.getProperties()).buildServiceRegistry();
sessionFactory = hibConfiguration.buildSessionFactory(serviceRegistry);
} catch( Exception e ) {
e.printStackTrace();
}
return sessionFactory.withOptions().openSession();
}
And this is what the LogEntry class object looks like (getters and setters omitted):
#Entity
#Table( name = "LogEntries" )
public class LogEntry {
public static int MESSAGE = 1;
public static int BOOKMAKER = 2;
public static int CLICKLOG = 3;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column( name = "lid" )
public int lid;
#Column( name = "id" )
public String id;
#Column( name = "date" )
public Date date;
#Column( name = "type" )
public int type;
#Column( name = "message" )
public String message;
#Column( name = "bookmaker" )
public String bookmaker;
#Column( name = "match_id" )
public int match_id;
#Column( name = "result" )
public String result;
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append(" lid = " + lid + "\n");
sb.append(" id = " + id + "\n");
sb.append(" date = " + date.toString() + "\n");
sb.append(" type = " + type + "\n");
sb.append(" message = " + message + "\n");
sb.append("bookmaker = " + bookmaker + "\n");
sb.append(" match_id = " + match_id + "\n");
sb.append(" result = " + result + "\n");
return sb.toString();
}
So, when I now run my tomcat instance and have a look on what did happen I get the following output:
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Apr 24, 2013 9:55:18 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Apr 24, 2013 9:55:18 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Logging of LogEntry into the database
lid = 0
id = 50569803719166097161
date = Mon Apr 22 21:01:53 CEST 2013
type = 1
message = MainVC
bookmaker = null
match_id = 0
result = null
Hibernate: insert into LogEntries (bookmaker, date, id, match_id, message, result, type) values (?, ?, ?, ?, ?, ?, ?)
Logging DONE
However after this having a look into my database reveals that nothing has been written to the table.
This is my table schema:
mysql> describe LogEntries;
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| lid | int(11) | NO | PRI | NULL | auto_increment |
| bookmaker | varchar(255) | YES | | NULL | |
| date | datetime | YES | | NULL | |
| id | varchar(255) | YES | | NULL | |
| match_id | int(11) | YES | | NULL | |
| message | varchar(255) | YES | | NULL | |
| result | varchar(255) | YES | | NULL | |
| type | int(11) | YES | | NULL | |
+-----------+--------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)
Has anybody got an idea what might cause this trouble. I'm clueless :(
The entity class should have getter and setter for the property.
As well after you are getting session, you need to begin your transaction.
http://docs.jboss.org/hibernate/orm/3.5/javadoc/org/hibernate/Session.html
Session sess = factory.openSession();
Transaction tx;
try {
tx = sess.beginTransaction();
//do some work
...
sess.save(entityObjectToBeinserted);
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
finally {
sess.close();
}
You need to declare get/set pairs for every property per the Hibernate documentation. These methods can be public, protected or private, but they must be present.