Hibernate not generating tables - java

Hibernate is not generating any tables when certain tables are added to hibernate.cfg.xml:
If I add:
<mapping class="org.hibernate.tutorial.annotations.Movie"/>
<mapping class="org.hibernate.tutorial.annotations.Actor"/>
No tables are generated at all, I already have:
<property name="hibernate.hbm2ddl.auto">update</property>
In hibernate.cfg.xml, and I have already tried variations of this, I know that the issue is with these classes as other classes work fine and are auto-generated when these are not added.
Actor
package org.hibernate.tutorial.annotations;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name="ACTOR")
public class Actor {
#Id #Column(name="ACTOR_ID")
private int id;
#Column(nullable=false, unique=true)
private String name;
#ManyToMany(
targetEntity=Movie.class,
cascade={CascadeType.PERSIST, CascadeType.MERGE}
)
#JoinTable(
name="Actor_Movie",
joinColumns=#JoinColumn(name="ACTOR_ID"),
inverseJoinColumns=#JoinColumn(name="MOVIE_ID")
)
private Set<Movie> films;
public Actor(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Movie> getFilms() {
return films;
}
public void setFilms(Set<Movie> films) {
this.films = films;
}
}
Movie
import java.sql.Time;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name="MOVIE")
public class Movie {
#Id #Column(name="MOVIE_ID")
private int id;
#Column(nullable=false,unique=true)
private String title;
#ManyToMany(
targetEntity=Track.class,
cascade={CascadeType.PERSIST, CascadeType.MERGE},
mappedBy = "movies"
)
private Set<Actor> actors;
private Time playTime;
public Movie(){
}
public int getId(){
return id;
}
public String getTitle(){
return title;
}
public Set<Actor> getActors(){
return actors;
}
public Time getTime(){
return playTime;
}
public void setTime(Time playTime){
this.playTime = playTime;
}
public void setId(int id){
this.id = id;
}
public void setTitle(String name){
this.title = name;
}
public void setActors(Set<Actor> actors){
this.actors = actors;
}
}
ResetDB
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import junit.framework.TestCase;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ResetDB extends TestCase{
private SessionFactory sessionFactory;
#Override
protected void setUp() throws Exception {
// A SessionFactory is set up once for an application
sessionFactory = new Configuration()
.configure() // configures settings from hibernate.cfg.xml
.buildSessionFactory();
}
#Override
protected void tearDown() throws Exception {
if ( sessionFactory != null ) {
sessionFactory.close();
}
}
public void testResetDB() {
Session session = sessionFactory.openSession();
session.beginTransaction();
try {
Query q = session.createSQLQuery("delete from ACTOR");
q.executeUpdate();
q = session.createSQLQuery("delete from MOVIE");
q.executeUpdate();
session.getTransaction().commit();
} catch (Exception e) {
System.out.println("Exception: "+e.getLocalizedMessage());
System.out.println("Transaction rolled back");
session.getTransaction().rollback();
}
session.close();
}
}
using hibernate-core-4.1.6

Related

"status": 404, "error": "Not Found", "path": "/GetProduct"

My controller class is -
package com.javatechie.crud.example.controller;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import com.javatechie.crud.example.entity.Product;
import com.javatechie.crud.example.service.ProductService;
public class ProductListController {
#Autowired
private ProductService service;
#GetMapping("/GetProduct")
public List<Product> addProducts(#RequestBody Product products) throws IOException, ClassNotFoundException, SQLException {
System.out.println("Inside addProducts controller method");
return service.saveProducts(1);
}
}
My entity class is -
package com.javatechie.crud.example.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="PRODUCT_TBL")
public class Product {
#Id
#GeneratedValue
private int id;
private String name;
private String quantity;
private double price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
JpaRepository implementation is -
package com.javatechie.crud.example.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="PRODUCT_TBL")
public class Product {
#Id
#GeneratedValue
private int id;
private String name;
private String quantity;
private double price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
And the service class is -
package com.javatechie.crud.example.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.javatechie.crud.example.entity.Product;
import com.javatechie.crud.example.repository.ProductRepository;
#Service
public class ProductService {
#Autowired
private ProductRepository repository;
public List<Product> saveProducts(int id) {
return repository.GetRepo(id);
}
}
And , the unexpected output which it is giving is -
Database table is as follows -
The output which I was expecting is the json body with sql record having id , name ,price,quantity . How can I achieve this output with native query only ? Please help.
You should add #RestController and #RequestMapping annotations for processing incoming REST requests.
#RestController
#RequestMapping("/api")
public class ProductListController {
#Autowired
private ProductService service;
#GetMapping("/GetProduct")
public List<Product> addProducts(#RequestBody Product products) throws IOException, ClassNotFoundException, SQLException {
System.out.println("Inside addProducts controller method");
return service.saveProducts(1);
}
}

findById() not working on spring boot and Jpa

My main class is :
package com.ashwin.jpafirst;
import com.ashwin.jpafirst.model.Person;
import com.ashwin.jpafirst.reposit.PersonJpaRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class JpafirstApplication implements CommandLineRunner {
private Logger logger= LoggerFactory.getLogger(this.getClass());
#Autowired
PersonJpaRepository personJpaRepository;
public static void main(String[] args)
{
SpringApplication.run(JpafirstApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
logger.info("User id is ",personJpaRepository.findById(2));
}
}
Person.java
package com.ashwin.jpafirst.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="person")
public class Person {
#Id
#GeneratedValue
private int id;
#Column(name="name")
private String name;
private String location;
private Date dateOfBirth;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public Person(int id, String name, String location, Date dateOfBirth) {
this.id = id;
this.name = name;
this.location = location;
this.dateOfBirth = dateOfBirth;
}
public Person() {
}
}
my application properties is:
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/jpaintro
spring.datasource.username = root
spring.datasource.password =
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
PersonJpaRepository.java
package com.ashwin.jpafirst.reposit;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.ashwin.jpafirst.model.Person;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository
#Transactional
public class PersonJpaRepository {
//connects to Databse
#PersistenceContext
EntityManager entityManager;
public Person findById(int id) {
return entityManager.find(Person.class, id);
}
}
I have also data saved in database as:
But when I try to receive the Person object by Id using
logger.info("User id is ",personJpaRepository.findById(2));
I am just getting as :
As Person object needs to print there,but the code is successfully compiling but I am not getting the information regarding the person.My code has no error but it is not retrieving the data.Why is the Person object not printing in the console?

Does not persist entity to db

When I try to add data to the database, the hibernate hangs on this point.
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Domain class
package org.jazzteam.domain.commentary;
import org.jazzteam.domain.id.Id;
import org.jazzteam.domain.event.Event;
import org.jazzteam.domain.user.SimpleUser;
import org.jazzteam.domain.user.User;
import javax.persistence.*;
/**
* #author Yura
* #version 1.0
*/
#Entity
#Table
public class Commentary extends Id {
#OneToOne(cascade = CascadeType.ALL)
private SimpleUser author;
private String description;
/*#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Event event;*/
private int rating;
public Commentary(){
}
public Commentary(SimpleUser author, String description, Event event, int rating){
this.author = author;
this.description = description;
/*this.event = event;*/
this.rating = rating;
}
public void setAuthor(SimpleUser author) {
this.author = author;
}
public void setDescription(String description) {
this.description = description;
}
/*public void setEvent(Event event) {
this.event = event;
}*/
public void setRating(int rating) {
this.rating = rating;
}
public User getAuthor() {
return author;
}
public String getDescription() {
return description;
}
/*public Event getEvent() {
return event;
}*/
public int getRating() {
return rating;
}
}
DAO
package org.jazzteam.dao.commentary;
import org.hibernate.SessionFactory;
import org.jazzteam.domain.commentary.Commentary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by Yura on 14.04.2017.
*/
#Repository
public class CommentaryDaoImpl implements CommentaryDao<Commentary> {
#Autowired
SessionFactory sessionFactory;
#Override
public void persist(Commentary entity) {
sessionFactory.getCurrentSession().persist(entity);
}
#Override
public void update(Commentary entiry) {
sessionFactory.getCurrentSession().update(entiry);
}
#Override
public void delete(Commentary entity) {
sessionFactory.getCurrentSession().delete(entity);
}
#Override
public Commentary findById(int id) {
return sessionFactory.getCurrentSession().get(Commentary.class, id);
}
#Override
public List<Commentary> findAll() {
return sessionFactory.getCurrentSession().createQuery("from Commentary ").list();
}
}
Service class
package org.jazzteam.service.commentary;
import org.jazzteam.dao.commentary.CommentaryDao;
import org.jazzteam.domain.commentary.Commentary;
import org.jazzteam.service.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by Yura on 14.04.2017.
*/
#org.springframework.stereotype.Service
public class CommentaryService implements Service<Commentary> {
#Autowired
CommentaryDao commentaryDao;
#Transactional
public void persist(Commentary entity) {
commentaryDao.persist(entity);
}
#Transactional
public void update(Commentary entity) {
commentaryDao.update(entity);
}
#Transactional
public void delete(int id) {
commentaryDao.delete(commentaryDao.findById(id));
}
#Transactional
public Commentary findById(int id) {
return (Commentary) commentaryDao.findById(id);
}
#Transactional
public List<Commentary> findAll() {
return commentaryDao.findAll();
}
}
I'm trying to add with this:
Commentary commentary = new Commentary(simpleUserService.findById(idAuthor),
comment,
eventService.findById(idEvent),
rate);
commentaryService.persist(commentary);
Id generate by class ID:
package org.jazzteam.domain.id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.MappedSuperclass;
/**
* #author Yura
* #version 1.0
*/
#MappedSuperclass
public abstract class Id {
#javax.persistence.Id
#GeneratedValue(strategy = GenerationType.AUTO)
protected int id;
public Id() {
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
What could be my mistake?
looks like you're trying to reinvent the wheel.
We might focus closely on your code, but I have a more general suggestion.
You already use Spring and Hibernate. Why not just use it as most people use it in 2017 - with Spring Data JPA.
You can google that and find lots of great tutorials about that topic.
Here is an official Spring introduction: https://spring.io/guides/gs/accessing-data-jpa/
a GitHub project with some examples: https://github.com/spring-projects/spring-data-examples
and a reference: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/
hope that helps :)
cheers
Solved this problem by changing:
#Override
public void persist(Commentary entity) {
sessionFactory.getCurrentSession().persist(entity);
}
to
#Override
public void persist(Commentary entity) {
sessionFactory.getCurrentSession().save(entity);
}
Perhaps it will be useful to someone :)

not-null property references a null or transient value in hibernate

I am getting below exception while executing my code. I am not hibernate expert and just started learning it. Please help. what changes need to be done for successful execution of below code. I have added all the code below.
Exception in thread "main" org.hibernate.PropertyValueException: not-null property references a null or transient value: hibernate.Student.officeAddress
at org.hibernate.engine.Nullability.checkNullability(Nullability.java:72)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:284)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:180)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:121)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:186)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:175)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
at hibernate.StoreData.main(StoreData.java:44)
Student.java
package hibernate;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table (name="student")
public class Student {
#Id
private int id;
private String firstName;
private String lastName;
private java.util.Date date;
#Embedded
#AttributeOverrides({
#AttributeOverride(name="pincode", column=#Column(name="Home_PIN_Code", nullable=false)),
#AttributeOverride(name="street", column=#Column(name="Home_Street", nullable=false)),
#AttributeOverride(name="city", column=#Column(name="Home_City", nullable=false))
})
private Address homeAddress;
#Embedded
private Address officeAddress;
public Address getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}
public Address getOfficeAddress() {
return officeAddress;
}
public void setOfficeAddress(Address officeAddress) {
this.officeAddress = officeAddress;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column (name="FirstNAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Lob
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Temporal (TemporalType.TIMESTAMP)
public java.util.Date getDate() {
return date;
}
public void setDate(java.util.Date date2) {
this.date = date2;
}
}
Address.java
package hibernate;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
#Column(name="Pincode",nullable=false)
private int pincode;
#Column(name="Street",nullable=false)
private String street;
#Column(name="City",nullable=false)
private String city;
public int getPincode() {
return pincode;
}
public void setPincode(int pincode) {
this.pincode = 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;
}
}
StoreData.java
package hibernate;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
public class StoreData {
public static void main(String[] args) {
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction t=session.beginTransaction();
Student e1=new Student();
e1.setId(1);
e1.setFirstName("Majid");
e1.setLastName("Khan");
e1.setDate(new Date());
Address ad1 = new Address();
ad1.setCity("Mumbai");
ad1.setPincode(400059);
ad1.setStreet("Marol Mahrishi Road");
e1.setHomeAddress(ad1);
Student e2=new Student();
e2.setId(2);
e2.setFirstName("Jayada");
e2.setLastName("Bano");
e2.setDate(new Date());
Address ad2 = new Address();
ad2.setCity("Hindaun");
ad2.setPincode(322230);
ad2.setStreet("Islam Colony");
e2.setOfficeAddress(ad2);
session.save(e1);
session.save(e2);
t.commit();
session.close();
System.out.println("successfully saved");
}
}
officeAddress can not be empty when you initialize values to the Student object
Change private int pincode to private Integer pincode as explained here Hibernate Embedded/Embeddable not null exception

ManyToOne annotation fails with Hibernate 4.1: MappingException

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();

Categories