I am using Eclipse and Derby database (with Embeeded Driver). As a starting point I am running the asadmin (from glassfish) to start-database from there. The database within eclipse can be pinged, as well as connected to just fine. Having started my EJB project which combines the session beans and entity beans I have ran into the following exception - java.lang.IllegalArgumentException: Unknown entity bean class: class model.Userbay, please verify that this class has been marked with the #Entity annotation.
Just few lines below this error i get pointed to this line of code - Userbay user = emgr.find(model.Userbay.class, username);
Although my feeling is that it could be a problem with the persistence.xml that causes it in the first place.
I would really appreciate any hints/help given towards fixing this annoying problem me and my friend are facing for quite a time now..
The following are the java/xml files;
Persistence.xml (which is stored under ejbModule/META-INF)
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="EJBAuctionv2">
<class>model.Userbay</class>
<class>model.Item</class>
<class>model.Category</class>
</persistence-unit>
</persistence>
I've also tried adding the following properties tag - however it grants another error org.apache.derby.client.am.SqlException: Schema 'ADRIAN' does not exist
<properties>
<property name="javax.persistence.jdbc.password" value="test" />
<property name="javax.persistence.jdbc.user" value="adrian" />
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeededDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:derby:C:/Users/Adrian/MyDB;create=true" />
</properties>
userRegistrationSB.java (Session Bean)
package auction;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Remote;
import javax.ejb.Singleton;
import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import model.Userbay;
/**
* Session Bean implementation class userRegistrationSB
*/
#Remote #Stateless
public class userRegistrationSB implements userRegistrationSBRemote {
//#EJB private Userbay user;
#PersistenceContext private EntityManager emgr;
/**
* Default constructor.
*/
public userRegistrationSB() {
// TODO Auto-generated constructor stub
System.out.println("TEST2");
}
#Override
public boolean registerUser(String username, String password, String email,
String firstname, String lastname) {
boolean registered = false;
System.out.println("Registering an user");
Userbay user = emgr.find(model.Userbay.class, username);
if (user != null) {
System.out.println("Username doesn't exist.");
registered = true;
} else {
registered = false;
System.out.println("Username already exists.");
}
return registered;
}
#Override
public boolean userExists(String username) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean userMatchesPassword(String username, String password) {
// TODO Auto-generated method stub
return false;
}
}
Userbay.java (Entity Bean)
package model;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
#Entity #Table (name = "Userbay")
/*#NamedQuery(name="Userbay.findAll", query="SELECT u FROM Userbay u")*/
public class Userbay implements Serializable {
private static final long serialVersionUID = 1L;
#Id #Column(name="USER_NAME")
private String userName;
private String email;
#Column(name="FIRST_NAME")
private String firstName;
#Column(name="LAST_NAME")
private String lastName;
#Column(name="PASSWORD")
private String password;
//bi-directional many-to-one association to Item
#OneToMany(mappedBy="userbay")
private List<Item> items;
public Userbay() {
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Item> getItems() {
return this.items;
}
public void setItems(List<Item> items) {
this.items = items;
}
public Item addItem(Item item) {
getItems().add(item);
item.setUserbay(this);
return item;
}
public Item removeItem(Item item) {
getItems().remove(item);
item.setUserbay(null);
return item;
}
}
I've also tried adding the following properties tag - however it
grants another error org.apache.derby.client.am.SqlException: Schema
'ADRIAN' does not exist
Have you checked if your database schema was actually created? If it did not, adding the following lines in your persistence.xml might help.
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
You may also want to undeploy your application manually or if it is your developer machine and this is the only application deployed merely delete content of the applications directory in your domain.
Related
I am trying to execute a basic hibernate application.However,I am consistently getting the error that is posted in the question.
Below posted is my project structure code:
Below is the code that is present in app.java
public class app {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Session session =hibernate_utils.getSessionFactory().openSession();
session.beginTransaction();
contact contact=new contact();
contact.setFirstname("xxx");
contact.setLastname("xxx");
contact.setEmail("xxxxxxx#gmail.com");
contact.setTelephone("xxxxxxxxxx");
session.save(contact);
session.getTransaction().commit();
System.out.println("saved");
}
}
Below posted is the code that is present in the contact.java file
package net.rishanth.contact.form;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Column;
import static javax.persistence.GenerationType.SEQUENCE;
#Entity
#Table(name = "contacts")
public class contact {
#Id
#GeneratedValue(strategy=SEQUENCE)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "firstname", nullable = false)
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
#Column(name = "lastname", nullable = false)
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Column(name = "email", nullable = false)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name = "telephone", nullable = false)
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
private String firstname;
private String lastname;
private String email;
private String telephone;
private Integer id;
}
Below posted is the code for my hiber_utils class present in service package.
package net.rishanth.contact.service;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class hibernate_utils {
private static final SessionFactory sessionfactory= buildSessionFatory();
#SuppressWarnings("deprecation")
private static SessionFactory buildSessionFatory(){
// TODO Auto-generated method stub
return new Configuration().configure().buildSessionFactory();
}
public static SessionFactory getSessionFactory()
{
return sessionfactory;
}
public static void shutdown()
{
getSessionFactory().close();
}
}
Below present is the hibernate.cnfg.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property
name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property
name="hibernate.connection.url">jdbc:oracle:thin:#127.0.0.1:1521:XE
</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect
</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">xxxxx</property>
<mapping class="net.rishanth.contact.form.contact"></mapping>
</session-factory>
</hibernate-configuration>
Below attached is my oracle screenshot
Any help would be highly appreciated.
Thanks!
You have annotated the Contact entity use SEQUENCE as strategy. But you have not specified which sequence should be used. (I believe this is the error you might be getting. If not, posting the exception stack trace will help.)
In this case, by default hibernate looks for a sequence named hibernate_sequence and creating a sequence with this name should help.
Or, In case you want hibernate to use a sequence (say, your_sequence_name) that you have already created then further qualifying the #Id attribute as below should help:
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="mySeq")
#GenericGenerator(name="mySeq", strategy="sequence",
parameters={
#Parameter(name="sequence_name", value="your_sequence_name")
})
Usually we need not to create the table/sequence in our DB, hibernate can manage the same.
For that you need to add below tag in your hibernate.cfg.xml
<property name="hbm2ddl.auto">create</property>
hbm2ddl.auto have few possible values:
create : When you create SessionFactory, hibernate drop everything(if exist) and create it again for you.
create-drop : create everything on start-up and drop them on shut-down
update : update the schema.
validate : validate the schema, makes no changes to the database.
Anyway, if you want to create table/sequence explicitly, you can create them.
But then while using #GeneratedValue you have to specify your sequence.
While running following program I am getting the error
org.hibernate.MappingException: Could not determine type for: java.util.Set, for columns: [org.hibernate.mapping.Column(ListOfAddress)]
I added the import javax.persistence.ElementCollection;
But I am getting the same error
Can anyone please suggest me any option?
HibernateTest.java
package src.com.hibernate.main;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.mapping.*;
import src.com.hibernate.Address;
import src.com.hibernate.UserDetails;
public class HibernateTest {
public static void main(String[] args)
{
UserDetails user = new UserDetails();
user.setUserName("Surendar");
Address addr = new Address();
addr.setStreet("Abith colony");
addr.setCity("Chennai");
addr.setState("TamilNAdu");
addr.setPincode("600015");
Address addr1= new Address();
addr1.setStreet("Anna Salai");
addr1.setCity("Chennaimain");
addr1.setState("TN");
addr1.setPincode("600033");
user.getListOfAddress().add(addr);
user.getListOfAddress().add(addr1);
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
}
UserDetails.java
package src.com.hibernate;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="UserTABLEaddress")
public class UserDetails
{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
private String userName;
#SuppressWarnings("rawtypes")
#ElementCollection
private Set<Address> ListOfAddress = new HashSet();
public Set<Address> getListOfAddress() {
return ListOfAddress;
}
public void setListOfAddress(Set<Address> listOfAddress) {
ListOfAddress = listOfAddress;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
Address.java
package src.com.hibernate;
import javax.persistence.Embeddable;
#Embeddable
public class Address
{
private String street;
private String city;
private String state;
private String pincode;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
}
Hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="src.com.hibernate.UserDetails"/>
</session-factory>
</hibernate-configuration>
I think your are mixing concepts. You try to use #Embeddable annotation in a class that is used in a many-to-one relationship. That is the cause of your error.
If you want to use ListOfAddress as an element collection, you have to define Address as an entity as well and configure the relationship correctly, for example:
...
#ElementCollection
#CollectionTable(name="address", joinColumns=#JoinColumn(name="userId"))
#Column(name="addresses")
private Set<Address> ListOfAddress = new HashSet<Address>();
...
And in Address Class
#Entity
#Table(name="address")
public class Address
...
There are plenty of examples through internet.
I faced similar problem, when i changed my java compiler version from 1.6 to 1.5 it worked for me.
SO probably check if that is the case with you
when i ran my code at first it worked correctly but later i am unable access those
tables?
Here is my code:-
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/navlic</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping class="dto.UserDetails"/>
</session-factory>
</hibernate-configuration>
Main class:-
package dto;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GenerationType;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.annotations.CollectionId;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateTest {
public static void main(String[] args) {
UserDetails ud=new UserDetails();
ud.setUserName("Second user");
Address homead=new Address();
homead.setCity("smg");
homead.setCountry("aa");
homead.setHouse("bb");
homead.setStreet("cc");
homead.setState("dd");
Address officead=new Address();
officead.setCity("smg");
officead.setCountry("ee");
officead.setHouse("ff");
officead.setStreet("gg");
officead.setState("hh");
ud.getAddr().add(homead);
ud.getAddr().add(officead);
SessionFactory sf;
ServiceRegistry sr;
Configuration cfg=new Configuration().configure();
sr=new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
sf=cfg.buildSessionFactory(sr);
Session s=sf.openSession();
s.beginTransaction();
s.save(ud);
s.getTransaction().commit();
s.close();
ud=null;
s=sf.openSession();
//if type is lazy it returns only the variables of that class no more reference variables.
//if type is Eager it returns all the elements of user class
ud=(UserDetails)s.get(UserDetails.class, 1);
System.out.println(ud.getAddr().size());
}
}
Model class:-
#Entity
public class UserDetails {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int UserId;
private String UserName;
#ElementCollection(fetch=FetchType.EAGER)
#JoinTable(name="User_Address",joinColumns=#JoinColumn(name="User_Id"))
#GenericGenerator(name="hilo-gen" ,strategy="hilo")
#CollectionId(columns={#Column(name="AddressId")},generator="hilo-gen",type=#Type(type="long"))
private Collection<Address> addr=new ArrayList<Address>();
public Collection<Address> getAddr() {
return addr;
}
public void setAddr(Collection<Address> addr) {
this.addr = addr;
}
public int getUserId() {
return UserId;
}
public void setUserId(int userId) {
UserId = userId;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
}
Address class is here :-
#Embeddable
public class Address {
#Column(name="Office_name")
private String House;
public String getHouse() {
return House;
}
public void setHouse(String house) {
House = house;
}
public String getStreet() {
return Street;
}
public void setStreet(String street) {
Street = street;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getState() {
return State;
}
public void setState(String state) {
State = state;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
#Column(name="street_name")
private String Street;
#Column(name="city_name")
private String City;
#Column(name="state_name")
private String State;
#Column(name="country_name")
private String Country;
}
when i try to run my code there is no error from hibernate but an mysql error is encountered I am new to mysql can anyone explain me in deatil the cause of this error and how to fix it.
thanks in advance
I am implementing a simple application to do CRUD operations, using Spring framework.
Source code:
User.java is the model class.
package com.vipin.model;
public class User {
private int ssn;
private String firstName;
private String lastName;
private String emailId;
public int getSsn() {
return ssn;
}
public void setSsn(int ssn) {
this.ssn = ssn;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
Dao layer:
package com.vipin.dao;
import com.vipin.model.User;
public interface DBOpsDao {
boolean add(User user);
boolean find(int ssnId);
}
The class which implements (skelton) implementation is:
package com.vipin.dao;
import java.sql.Connection;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.vipin.model.User;
public class DefaultDBOpsDaoImpl implements DBOpsDao {
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
#Resource(name="dataSource")
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
System.out.println("Datasource value is " + dataSource);
}
public boolean add(User user) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
return false;
}
public boolean find(int ssnId) {
// TODO Auto-generated method stub
return false;
}
}
Sample Main class:
package com.vipin.app;
import com.vipin.dao.DBOpsDao;
import com.vipin.dao.DefaultDBOpsDaoImpl;
import com.vipin.model.User;
public class MainApp {
public static void main(String[] args) {
System.out.println("Inside main...");
DBOpsDao dao = new DefaultDBOpsDaoImpl();
User user = new User();
user.setFirstName("xxx");
user.setLastName("yyy");
user.setSsn(1);
user.setEmailId("xxx.yyy#example.com");
dao.add(user);
}
}
I am using maven to build this, so the java source code is in:
src/main/java (top level package com.vipin)
When i run this program it is throwing exception complaining that spring.xml doesn't exist. I
used ApplicationContext, one of implementation ClassPathXmlApplicationContext.
In which location do i need to put spring.xml file?
Any inputs would be helpful.
You will need to add spring.xml file at the location - src/main/resources folder. You can have your directory structure inside this directory as - src/main/resources/com/vipin/dao.
src/main/java directory is preferred for java classes.
If you are debugging from eclipse, make sure that you are adding your folder in the project's classpath.
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
If you create your maven project using maven archetype and you import into eclipse, you need to edit your .classpath file.
You have to initilalize application context properly in your main method. You can check this link for example.
Place the xml file at the root of your classpath
For maven that is src/main/resources/ if the directory doesn't exist yet, create it.
src/main/resources/applicationContext.xml
Also src/main/resources/spring/ works as well.
Using Hibernate 4.1.1.Final.
When I try to add #ManyToOne, schema creation fails with: org.hibernate.MappingException: Could not instantiate persister org.hibernate.persister.entity.SingleTableEntityPersister
User.java:
#Entity
public class User {
#Id
private int id;
public int getId() {return id;}
public void setId(int id) {this.id = id;}
#ManyToOne
Department department;
public Department getDepartment() {return department;}
public void setDepartment(Department department) {this.department = department;}
}
Department.java
#Entity
public class Department {
#Id
private int departmentNumber;
public int getDepartmentNumber() {return departmentNumber;}
public void setDepartmentNumber(int departmentNumber) {this.departmentNumber = departmentNumber;}
}
hibernate.properties:
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/dbname
hibernate.connection.username=user
hibernate.connection.password=pass
hibernate.connection.pool_size=5
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.hbm2ddl.auto=create
init (throwing exception):
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().buildServiceRegistry();
sessionFactory = new MetadataSources(
serviceRegistrY.addAnnotatedClass(Department.class).addAnnotatedClass(User.class).buildMetadata().buildSessionFactory();
exception throwed at init:
org.hibernate.MappingException: Could not instantiate persister org.hibernate.persister.entity.SingleTableEntityPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:174)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:148)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:820)
at org.hibernate.metamodel.source.internal.SessionFactoryBuilderImpl.buildSessionFactory(SessionFactoryBuilderImpl.java:65)
at org.hibernate.metamodel.source.internal.MetadataImpl.buildSessionFactory(MetadataImpl.java:340)
I have tried adding some other annotations, but shouldn't the defaults work and create the tables and foreign key? If I remove the department from User, tables get generated fine.
Thanks in advance!
You are using features not yet complete. Everything in org.hibernate.metamodel is targetting 5.0.
http://docs.jboss.org/hibernate/orm/4.1/javadocs/org/hibernate/metamodel/package-summary.html
#Entity
public class User {
#Id
private int id;
public int getId() {return id;}
public void setId(int id) {this.id = id;}
#ManyToOne
Department department;
public Department getDepartment() {return department;}
public void setDepartment(Department department) {this.department = department;}
}
#Entity
public class Department {
#Id
private int departmentNumber;
#OneToMany(mappedBy="department")
private Set<User> user;
public Set<User> getUser() {
return user;
}
public void setUser(Set<User> user) {
this.user = user;
}
public int getDepartmentNumber() {return departmentNumber;}
public void setDepartmentNumber(int departmentNumber) {this.departmentNumber = departmentNumber;}
}
You have to add a set to the Department entity and map OneToMany Relationship with the User
My example:
User.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class User {
private int id;
private String userName;
private String password;
#Id
#GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Column
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
TraceLog.java
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
#Entity
public class TraceLog {
private int id;
private User user;
private String tokenId;
private String variable;
private String value;
private Date traceTime;
#Id
#GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#ManyToOne(cascade = CascadeType.ALL)
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Column
public String getTokenId() {
return tokenId;
}
public void setTokenId(String tokenId) {
this.tokenId = tokenId;
}
#Column
public String getVariable() {
return variable;
}
public void setVariable(String variable) {
this.variable = variable;
}
#Column
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Column
public Date getTraceTime() {
return traceTime;
}
public void setTraceTime(Date traceTime) {
this.traceTime = traceTime;
}
}
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/sessiontest</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">mysql</property>
<property name="hibernate.connection.pool_size">1</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.cpviet.example.session.model.User" />
<mapping class="com.cpviet.example.session.model.TraceLog" />
</session-factory>
</hibernate-configuration>
HibernateUtil.java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
private SessionFactory sessionFactory = null;
private static HibernateUtil instance = null;
private HibernateUtil() {
}
public static HibernateUtil getInstance() {
if (instance == null) {
instance = new HibernateUtil();
}
return instance;
}
public SessionFactory getSessionFactory() {
if (sessionFactory == null) {
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
}
}
How to use:
Session session = HibernateUtil.getInstance().getSessionFactory().openSession();
user = (User) session.get(User.class, (Integer)1);
session.close();
or
Session session = HibernateUtil.getInstance().getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
TraceLog traceLog = new TraceLog();
traceLog.setTokenId(tokenId);
traceLog.setVariable("var1");
traceLog.setValue("val1");
traceLog.setUser(user);
traceLog.setTraceTime(new Date());
session.save(traceLog);
transaction.commit();
session.close();