I can't get the currentSession - java
I'm a beginner in Java EE programming. I got this error message when I tried to save an employee in a database:
java.lang.NullPointerException
at ma.lezar.ge.dao.EmployeesDAO.getCurrentSession(EmployeesDAO.java:48)
at ma.lezar.ge.dao.EmployeesDAO.save(EmployeesDAO.java:59)
at ma.lezar.ge.service.ServiceEmployees.save(ServiceEmployees.java:26)
at ma.lezar.ge.bean.InscrirBean.valider(InscrirBean.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 28 more
This is employeeDAO.java
package ma.lezar.ge.dao;
import java.util.List;
import java.util.Set;
import ma.lezar.ge.model.Employees;
import org.hibernate.Hibernate;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository("EmployeesDAO")
#Transactional
public class EmployeesDAO implements IEmployeesDAO {
private static final Logger log = LoggerFactory
.getLogger(EmployeesDAO.class);
// property constants
public static final String NOM = "nom";
public static final String NUM = "num";
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
protected void initDao() {
// do nothing
}
public void save(Employees transientInstance) {
//System.out.println(getCurrentSession().toString());
// log.debug("saving Employees instance");
// try {
getCurrentSession().save(transientInstance);
// log.debug("save successful");
// } catch (RuntimeException re) {
// log.error("save failed", re);
// throw re;
// }
}
public void delete(Employees persistentInstance) {
log.debug("deleting Employees instance");
try {
getCurrentSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public Employees findById(java.lang.Integer id) {
log.debug("getting Employees instance with id: " + id);
try {
Employees instance = (Employees) getCurrentSession().get(
"ma.lezar.ge.model.Employees", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findAll() {
log.debug("finding all Employees instances");
try {
String queryString = "from Employees";
Query queryObject = getCurrentSession().createQuery(queryString);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public static EmployeesDAO getFromApplicationContext(ApplicationContext ctx) {
return (EmployeesDAO) ctx.getBean("EmployeesDAO");
}
}
Employee.java
package ma.lezar.ge.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Employees entity. #author MyEclipse Persistence Tools
*/
#Entity
#Table(name = "employees", catalog = "gest_emp")
public class Employees implements java.io.Serializable {
// Fields
private Integer id;
private String nom;
private Integer num;
private Set<Compte> comptes = new HashSet<Compte>(0);
// Constructors
/** default constructor */
public Employees() {
}
/** minimal constructor */
public Employees(String nom, Integer num) {
this.nom = nom;
this.num = num;
}
/** full constructor */
public Employees(String nom, Integer num, Set<Compte> comptes) {
this.nom = nom;
this.num = num;
this.comptes = comptes;
}
// Property accessors
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "nom", nullable = false, length = 50)
public String getNom() {
return this.nom;
}
public void setNom(String nom) {
this.nom = nom;
}
#Column(name = "num", nullable = false)
public Integer getNum() {
return this.num;
}
public void setNum(Integer num) {
this.num = num;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "employees")
public Set<Compte> getComptes() {
return this.comptes;
}
public void setComptes(Set<Compte> comptes) {
this.comptes = comptes;
}
}
InscrirBean.java
package ma.lezar.ge.bean;
import java.io.Serializable;
import javax.ejb.EJB;
import org.springframework.beans.factory.annotation.Autowired;
import ma.lezar.ge.dao.EmployeesDAO;
import ma.lezar.ge.model.Employees;
import ma.lezar.ge.service.IServiceEmployees;
import ma.lezar.ge.service.ServiceEmployees;
public class InscrirBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Autowired
private ServiceEmployees serviceEmployees;
private String nom;
private Integer num;
public String valider()
{
serviceEmployees = new ServiceEmployees();
serviceEmployees.save(new Employees(nom, num));
return "success";
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
}
ServiceEmployee.java
package ma.lezar.ge.service;
import java.util.List;
import javax.annotation.Resource;
import ma.lezar.ge.dao.EmployeesDAO;
import ma.lezar.ge.dao.IEmployeesDAO;
import ma.lezar.ge.model.Employees;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
#Service("serviceEmployees")
public class ServiceEmployees implements IServiceEmployees {
#Resource
private EmployeesDAO employeesDao;
public void save(Employees transientInstance) {
employeesDao = new EmployeesDAO();
employeesDao.save(transientInstance);
}
public void delete(Employees persistentInstance) {
employeesDao.delete(persistentInstance);
}
public Employees findById(java.lang.Integer id) {
Employees instance = (Employees) employeesDao.findById(id);
return instance;
}
public List findAll()
{
return employeesDao.findAll();
}
}
HibernateSessionFactory.java
package ma.lezar.ge.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {#link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry;
static {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* #return Session
* #throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* #throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" xmlns:tx="http://www.springframework.org/schema/tx">
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="url"
value="jdbc:mysql://localhost:3306/gest_emp">
</property>
<property name="username" value="root"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>ma.lezar.ge.model.Compte</value>
<value>ma.lezar.ge.model.Employees</value></list>
</property></bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="CompteDAO" class="ma.lezar.ge.dao.CompteDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="EmployeesDAO" class="ma.lezar.ge.dao.EmployeesDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
</beans>
You're instantiating employeesDao yourself instead of letting Spring manage the DI for that class. Remove the statement
employeesDao = new EmployeesDAO();
in ServiceEmployees.
Related
Enity is not mapped [select o from Type o]
I'm trying to create a small project with hibernate, but i got that error "Type is not mapped [select o from Type o]", I added mapping in hibernate.cfg.xml but still error. Type.java: package com.formation.gestionprojet.doa.entity; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; #Entity #Table(name="Type") public class Type implements Serializable { /** * */ private static final long serialVersionUID = 1L; #Id private Long id; private String name; private String description; private String active; public Type() { super(); // TODO Auto-generated constructor stub } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getActive() { return active; } public void setActive(String active) { this.active = active; } } hibernate.org.xml: <?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> <!-- database connection setting --> <property name ="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/gestion_projet?createDatabaseIfNotExist=true</property> <property name="connection.username">root</property> <property name= "connection.password">root</property> <!-- Dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Disable the second level cache --> <property name="cache.provider_class" >org.hibernate.cache.NoCacheProvider</property> <!-- echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drope and re-create the database --> <property name="hbm2ddl.auto">update</property> <!-- mapping --> <mapping class= "com.formation.gestionprojet.doa.entity.Type"/> </session-factory> </hibernate-configuration> hibernateUtil.java: package com.formation.gestionprojet.utils; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; #SuppressWarnings("deprecation") public class HibernateUtil { private static SessionFactory sessionFactory; private static ServiceRegistry serviceRegistry; static { try { Configuration configuration = new Configuration(); configuration.configure("config/hibernate.cfg.xml"); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (HibernateException ex) { System.err.println("Error creating Session: " + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static Session openSession() { return sessionFactory.openSession(); } public static Session getCurrentSession() { return sessionFactory.getCurrentSession(); } public static void close(){ if(sessionFactory!=null){ sessionFactory.close(); } } } Test.Java package com.formation.gestionprojet.utils; import org.hibernate.Session; public class Test { static Session session = HibernateUtil.openSession(); public static void main(String[] args) { session.createQuery("select o from Type o").list(); } }
solved ! the problem was the version of hibernate that I used so I change it, a change in HibernateUtil.
Hibernate Not retrieving the data
Iam trying to build a sample application with JAXRS/Hibernate. I have sample data in my database,but i could not retrieve it.Please verify my code and let me know where Iam making error. Entity class package org.cricket.cricketstats.data; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; #Table(name="player_info") #Entity public class PlayerInfo { #Id #Column(name="player_id") #GeneratedValue(strategy = GenerationType.IDENTITY) private long playerId; #Column(name="player_name") private String playerName; #Column(name="player_role") private String playerRole; #Column(name="player_batting_style") private String playerBattingStyle; #Column(name="player_bowling_style") private String playerBowlingStyle; #Column(name="player_image") private String playerImage; #Column(name="player_profile_desc") private String playerProfile; public PlayerInfo(){ } public PlayerInfo(long playerId, String playerName, String playerRole, String playerBattingStyle, String playerBowlingStyle, String playerImage, String playerProfile) { super(); this.playerId = playerId; this.playerName = playerName; this.playerRole = playerRole; this.playerBattingStyle = playerBattingStyle; this.playerBowlingStyle = playerBowlingStyle; this.playerImage = playerImage; this.playerProfile = playerProfile; } public long getPlayerId() { return playerId; } public void setPlayerId(long playerId) { this.playerId = playerId; } public String getPlayerName() { return playerName; } public void setPlayerName(String playerName) { this.playerName = playerName; } public String getPlayerRole() { return playerRole; } public void setPlayerRole(String playerRole) { this.playerRole = playerRole; } public String getPlayerBattingStyle() { return playerBattingStyle; } public void setPlayerBattingStyle(String playerBattingStyle) { this.playerBattingStyle = playerBattingStyle; } public String getPlayerBowlingStyle() { return playerBowlingStyle; } public void setPlayerBowlingStyle(String playerBowlingStyle) { this.playerBowlingStyle = playerBowlingStyle; } public String getPlayerImage() { return playerImage; } public void setPlayerImage(String playerImage) { this.playerImage = playerImage; } public String getPlayerProfile() { return playerProfile; } public void setPlayerProfile(String playerProfile) { this.playerProfile = playerProfile; } } Rest Resource package org.cricket.cricketstats.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.cricket.cricketstats.data.PlayerInfoDAO; import org.cricket.cricketstats.model.PlayerInfoBean; #Path("players") public class CricketResources { PlayerInfoBean playerInfoBean= new PlayerInfoBean(); #GET #Path("{playerId}") #Produces(MediaType.APPLICATION_JSON) public PlayerInfoBean getPlayerDetails(#PathParam("playerId") long id) { PlayerInfoDAO dao= new PlayerInfoDAO(); dao.getPlayerInfo(); playerInfoBean.setPlayerId(id); return playerInfoBean; } } Config file <?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> <!-- Connection settings --> <property name="hibernate.connection.driver_class">org.postgresql.Driver</property> <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/cricket</property> <property name="hibernate.connection.username">postgres</property> <property name="hibernate.connection.password">postgres</property> <!-- SQL dialect --> <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property> <!-- Print executed SQL to stdout --> <property name="show_sql">true</property> <!-- validate all database on startup --> <property name="hibernate.hbm2ddl.auto">validate</property> <!-- Annotated entity classes --> <mapping class="org.cricket.cricketstats.data.PlayerInfo"/> </session-factory> </hibernate-configuration> DAO class package org.cricket.cricketstats.data; import java.util.List; import org.cricket.cricketstats.model.PlayerInfoBean; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; public class PlayerInfoDAO { public void getPlayerInfo(){ Configuration config=new Configuration().configure(); ServiceRegistry serviceRegistry= new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build(); //StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(config.getProperties()); // SessionFactory factory = config.buildSessionFactory(builder.build()); SessionFactory factory = config.buildSessionFactory(serviceRegistry); Session session = factory.openSession(); Transaction tx =session.beginTransaction(); List infoList=session.createQuery("FROM PlayerInfo").list(); tx.commit(); session.close(); System.out.println(infoList.get(0).getPlayerName()); } } **I have tried to give full path also in query **
The way is used by you to building a session factory is not correct for Hibernate 5. It can be used only for Hibernate 4. Use this instead SessionFactory factory = new Configuration().configure().buildSessionFactory();
org.hibernate.MappingException: Unknown entity - What is the root cause?
I am new to hibernate. i am following a tutorial and trying to execute a simple code but I am getting below error. org.hibernate.MappingException: Unknown entity: I am using annotations and configuration file also did exactly according the tutorials. I have googled but didn't get the correct answer This is my code package org.anne; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class Demo { public static void main(String[] args) { Paper p = new Paper(); p.setPname("indu"); SessionFactory sf = HibernateUtil.getSessionFactory(); Session ses = sf.openSession(); Transaction tr = ses.beginTransaction(); ses.save(p); tr.commit(); ses.close(); sf.close(); } } package org.anne; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class HibernateUtil { static SessionFactory sf; public static SessionFactory getSessionFactory() { Configuration cf = new Configuration(); cf.configure("hibernate.cfg.xml"); StandardServiceRegistryBuilder srv = new StandardServiceRegistryBuilder(); StandardServiceRegistry sr = srv.applySettings(cf.getProperties()).build(); sf = cf.buildSessionFactory(sr); return sf; } } package org.anne; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; #Entity #Table(name = "PAPER") public class Paper { int pid; String pname; #Id #Column(name = "PID") #GeneratedValue(strategy = GenerationType.AUTO) public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } #Column(name = "PNAME") public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } } <?xml version="1.0"?> <!DOCTYPE hibernate-configuration SYSTEM "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/test</property> <property name = "connection.username">root</property> <property name = "connection.password">abc123</property> <property name = "hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name = "hibernate.show_sql">true</property> <mapping class = "org.anne.Paper" /> </session-factory> </hibernate-configuration>
If you boot Hibernate yourself, make sure to use the AnnotationConfiguration class instead of the Configuration class. Here is an example using the (legacy) HibernateUtil approach: package hello; import org.hibernate.*; import org.hibernate.cfg.*; import test.*; import test.animals.Dog; public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { sessionFactory = new AnnotationConfiguration() .configure().buildSessionFactory(); } catch (Throwable ex) { // Log exception! throw new ExceptionInInitializerError(ex); } } public static Session getSession() throws HibernateException { return sessionFactory.openSession(); } } More here https://docs.jboss.org/hibernate/stable/annotations/reference/en/html/ch01.html#setup-configuration
NoClassDefFoundError - ClassLoaderDelegate - Hibernate
I am new to Java Hibernate. I setup a dynamic web project in eclipse and trying to insert a row in mysql db. I am getting the following error when I run my code on server. java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/ClassLoaderDelegate org.hibernate.boot.internal.MetadataBuilderImpl.(MetadataBuilderImpl.java:127) org.hibernate.boot.MetadataSources.getMetadataBuilder(MetadataSources.java:135) org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:655) My hibernate.cfg.xml <session-factory> <!-- Database connection settings --> <property name='connection.driver_class'>com.mysql.jdbc.Driver</property> <property name='connection.url'>jdbc:mysql://localhost:3306/bornscientific</property> <property name='connection.username'>root</property> <property name='connection.password'></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> <!-- Echo all executed SQL to stdout --> <property name='show_sql'>true</property> <!-- Mapping files --> <mapping class="com.bornscientific.persistence.beans.Tags"/> </session-factory> My entity class package com.bornscientific.persistence.beans; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; #Entity #Table(name = "TAGS") public class Tags implements Serializable { private Long id; private String name; public Tags() { } #Id #SequenceGenerator(name="seq1",sequenceName="HIB_SEQ") #GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq1") #Column(name = "TAG_ID", unique = true, nullable = false) public Long getId() { return id; } public void setId(Long id) { this.id = id; } #Column(name = "NAME", unique = true, length = 100, nullable = false) public String getName() { return name; } public void setName(String name) { this.name = name; } } And my main method is public static void test() throws Exception { try { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx = session.getTransaction(); tx.begin(); Tags tags = new Tags(); tags.setName("TAG_1"); session.save(tags); tx.commit(); System.out.println("Saved successfully..."); } catch(Exception e) { //System.out.println(e) e.printStackTrace(); } } HibernateUtil.java package com.bornscientific.persistence; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { Configuration configuration = new Configuration().configure(); StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder(); serviceRegistryBuilder.applySettings(configuration.getProperties()); ServiceRegistry serviceRegistry = serviceRegistryBuilder.build(); return configuration.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); ex.printStackTrace(); throw ex; } } public static SessionFactory getSessionFactory() { return sessionFactory; } } And this is the library referenced. Please help me fix this issue. I have searched through google and could not find a solution.
java hibernate the table not created even with <property name="hibernate.hbm2ddl.auto">update</property>
/** * Description of bankbranchcontactdetailsBean * * #author Vishal Jain */ package com.beans; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Id; import javax.persistence.Column; import javax.persistence.Temporal; import javax.persistence.UniqueConstraint; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import java.io.Serializable; import java.util.Date; #Entity(name = "bankbranchcontactdetails") #Table(name = "bankbranchcontactdetails", schema = "stserptest", uniqueConstraints = { #UniqueConstraint(columnNames = "BankBranchContactId") }) #TableGenerator(name = "bankbranchcontactdetailsgen", table = "bankbranchcontactdetails", pkColumnName = "BankBranchContactId") public class bankbranchcontactdetailsBean extends SuperBeanClass implements SuperBeanInterface, Serializable { #Id #GeneratedValue(strategy = GenerationType.AUTO) #Column(columnDefinition="mysql->int(10) unsigned", name = "BankBranchContactId", precision = 10, scale = 0, nullable = false, unique = true) private Integer Id; #Column(columnDefinition="mysql->int(10) unsigned", name = "BankBranchId", precision = 10, scale= 0, nullable = false) private Integer _BankBranchId; #Column(columnDefinition="mysql->enum('Phone','Mobile','Fax','Telex')", name = "ContactType", length = 6, nullable = false) private String _ContactType; #Column(columnDefinition="mysql->varchar(20)", name = "Contact", length = 20, nullable = false) private String _Contact; public bankbranchcontactdetailsBean() { _BankBranchId = 0; _ContactType = ""; _Contact = ""; } public bankbranchcontactdetailsBean(Integer __BankBranchId, String __ContactType, String __Contact, Integer __MyCompanyId) { _BankBranchId = __BankBranchId; _ContactType = __ContactType; _Contact = __Contact; _MyCompanyId = __MyCompanyId; } public int getBankBranchContactId() { return Id; } public Integer getBankBranchId() { return _BankBranchId; } public String getContactType() { return _ContactType; } public String getContact() { return _Contact; } public void setBankBranchContactId(int NewValue) { Id = NewValue; } public void setBankBranchId(Integer NewValue) { _BankBranchId = NewValue; } public void setContactType(String NewValue) { _ContactType = NewValue; } public void setContact(String NewValue) { _Contact = NewValue; } } <?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.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">MimosaTorpedo</property> <property name="hibernate.default_schema">stserptest</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="show_sql">true</property> <mapping class="com.stserp.beans.bankbranchcontactdetailsBean" /> </session-factory> </hibernate-configuration> /** * Description of ManagerClass * * #author Vishal Jain */ package com.beans; import java.util.ArrayList; import javax.swing.JOptionPane; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; public class ManagerClass { private static SessionFactory factory = null; private static ManagerClass _ManagerClass = null; public static SessionFactory createSessionFactory() { SessionFactory sessionFactory; Configuration configuration = new Configuration(); configuration.configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() .applySettings(configuration.getProperties()) .buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } public static SessionFactory getSessionFactory() { return factory; } public static ManagerClass getInstance() throws ExceptionInInitializerError { try { if (factory == null) { factory = createSessionFactory(); } if (_ManagerClass == null) { _ManagerClass = new ManagerClass(); } } catch (Throwable ex) { JOptionPane.showMessageDialog( null, "Failed to create sessionFactory object...\n" + ex.getMessage(), "Error...", 0); throw new ExceptionInInitializerError(ex); } finally { return _ManagerClass; } } public ArrayList<Integer> SaveBeansList(Session session, String entityName, ArrayList<? extends SuperBeanClass> BeansList) throws HibernateException { ArrayList<Integer> IDs = null; try { IDs = new ArrayList<Integer>(); for (SuperBeanClass element : BeansList) { IDs.add((Integer) session.save(entityName, element)); } } catch (HibernateException e) { throw e; } return IDs; } public ArrayList<? extends SuperBeanClass> LoadTable(Session session, String TableName) throws HibernateException { ArrayList<? extends SuperBeanClass> beansList = null; try { beansList = (ArrayList<? extends SuperBeanClass>) session .createQuery("FROM " + TableName).list(); } catch (HibernateException e) { throw e; } return beansList; } public ArrayList<?> LoadConditional(Session session, String _query) throws HibernateException { ArrayList<?> beansList = null; try { beansList = (ArrayList<? extends SuperBeanClass>) session .createQuery(_query).list(); } catch (HibernateException e) { throw e; } return beansList; } public SuperBeanInterface LoadById(Session session, Class className, Integer ID) throws HibernateException { SuperBeanInterface BeanInterface = null; try { BeanInterface = (SuperBeanInterface) session.get(className, ID); } catch (HibernateException e) { throw e; } return BeanInterface; } public void DeleteById(Session session, Class className, Integer ID) throws HibernateException { try { session.delete(session.get(className, ID)); } catch (HibernateException e) { throw e; } } } /** * Description of SuperBeanClass * * #author Vishal Jain */ package com.beans; public class SuperBeanClass { public SuperBeanClass() { } } /** * Description of SuperBeanInterface * * #author Vishal Jain */ package com.beans; public interface SuperBeanInterface { } I dont know what wrong I am doing, but even though the code gets executed fine, the Table named 'bankbranchcontactdetails' does not get created, here. The database I am using is MySQL. Can anybody help me with that
Trying Changing Column Definitions here, is a good idea. The Problem was with the database specific directions 'mysql->'. I am might be using it wrongly. But for now I tried removing it and it worked.