I am using this simple Hibernate Mapping xml to create an entity
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<hibernate-mapping>
<class entity-name="FirstTestType">
<property column="createdOn" name="java.sql.Timestamp" type="java.sql.Timestamp"/>
<id column="id" name="id" type="java.lang.Long">
<generator class="identity"/>
</id>
<property column="modifiedOn" name="java.sql.Timestamp" type="java.sql.Timestamp"/>
<property column="testString" length="100" name="java.lang.String" type="java.lang.String"/>
<property column="testInt" name="int" type="int"/>
<property column="testBoolean" name="boolean" type="boolean"/>
<property column="testLong" name="long" type="long"/>
</class>
</hibernate-mapping>
Though my schema is effectively created when I use SchemaExport
final SchemaExport export = new SchemaExport(getHibernateConfigurationForSchema());
export.create(true, true);
When I try to create a sessionfactory I am getting this exception
org.hibernate.MappingException: Duplicate property mapping of java.sql.Timestamp found in FirstTestType
at org.appops.entityStore.hibernate.session.HibernateSessionFactoryProvider.setupSchemaSessionFactory(HibernateSessionFactoryProvider.java:78)
at org.appops.entityStore.hibernate.session.HibernateSessionFactoryProviderTest.testSessionCreation(HibernateSessionFactoryProviderTest.java:110)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:606)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.hibernate.MappingException: Duplicate property mapping of java.sql.Timestamp found in FirstTestType
at org.hibernate.mapping.PersistentClass.checkPropertyDuplication(PersistentClass.java:483)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:473)
at org.hibernate.mapping.RootClass.validate(RootClass.java:235)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1362)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1865)
at org.appops.entityStore.hibernate.session.HibernateSessionFactoryProvider.setupSchemaSessionFactory(HibernateSessionFactoryProvider.java:74)
... 11 more
Can you help me figure out whats wrong with the Mapping xml ?
Change names in properties;
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<hibernate-mapping>
<class entity-name="FirstTestType">
<property column="createdOn" name="nameCreatedOn" type="java.sql.Timestamp"/>
<id column="id" name="id" type="java.lang.Long">
<generator class="identity"/>
</id>
<property column="modifiedOn" name="nameModifiedOn" type="java.sql.Timestamp"/>
<property column="testString" length="100" name="nameTestString" type="java.lang.String"/>
<property column="testInt" name="nameTestInt" type="int"/>
<property column="testBoolean" name="nameTestBoolean" type="boolean"/>
<property column="testLong" name="nameTestLong" type="long"/>
</class>
</hibernate-mapping>
Your class look like;
package basari.util;
public class FirstTestType {
private Date nameCreatedOn;
private int nameId;
private String nameModifiedOn;
private String nameTestString;
private int nameTestInt;
private Boolean nameTestBoolean;
private Long nameTestLong;
public FirstTestType(){
}
public Date getNameCreatedOn() {
return nameCreatedOn;
}
public void setNameCreatedOn(Date nameCreatedOn) {
this.nameCreatedOn = nameCreatedOn;
}
public int getNameId() {
return nameId;
}
public void setNameId(int nameId) {
this.nameId = nameId;
}
public String getNameModifiedOn() {
return nameModifiedOn;
}
public void setNameModifiedOn(String nameModifiedOn) {
this.nameModifiedOn = nameModifiedOn;
}
public String getNameTestString() {
return nameTestString;
}
public void setNameTestString(String nameTestString) {
this.nameTestString = nameTestString;
}
public int getNameTestInt() {
return nameTestInt;
}
public void setNameTestInt(int nameTestInt) {
this.nameTestInt = nameTestInt;
}
public Boolean getNameTestBoolean() {
return nameTestBoolean;
}
public void setNameTestBoolean(Boolean nameTestBoolean) {
this.nameTestBoolean = nameTestBoolean;
}
public Long getNameTestLong() {
return nameTestLong;
}
public void setNameTestLong(Long nameTestLong) {
this.nameTestLong = nameTestLong;
}
}
Related
when i want to save my object it throws unknown entity exception.
tnx in advance
Exception in thread "main" org.hibernate.MappingException: Unknown
entity: com.simpleProgrammer.User at
org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:618)
at
org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1595)
at
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
at
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at
org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at
org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:667)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:659) at
org.hibernate.internal.SessionImpl.save(SessionImpl.java:654) at
com.simpleProgrammer.Program.main(Program.java:22)
my hibernate.cfg.xml file is here
<?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="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/protein_tracker</property>
<property name="hibernate.connection.username">root</property>
<!-- <property name="hibernate.default_schema"></property> -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping resource="com/simpleProgrammer/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
my User.hbm.xml mapping file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping">
<hibernate-mapping>
<class name="com.simpleProgrammer.User" table="USERS">
<id name="id" type="int" column="id">
<generator class="identity" />
</id>
<property name="name" column="NAME" type="string" />
<component name="proteinData">
<property name="total" column="TOTAL" type="int" />
<property name="goal" column="GOAL" type="int" />
</component>
<set name="history" table="USER_HISTORY">
<key column="ID"/>
<composite-element class="com.simpleProgrammer.UserHistory">
<property name="entryTime" type="date" column="ENTRY_TIME"/>
<property name="entry" type="string" column="ENTRY"/>
</composite-element>
</set>
</class>
</hibernate-mapping>
my progaram.java
package com.simpleProgrammer;
import java.util.Date;
import org.hibernate.Session;
public class Program {
public static void main(String[] args) {
Session session = new HibernateUtilities().getSessionFactory().openSession();
System.out.println("Session Opened!!!");
session.beginTransaction();
System.out.println("Transaction begined!");
User user = new User();
user.setName("Joe");
user.getHistory().add(new UserHistory(new Date(), "Setting Name to Joe"));
user.getProteinData().setGoal(250);
user.getHistory().add(new UserHistory(new Date(), "Setting Goal to 250!"));
System.out.println("Setting user Object");
session.save(user);
System.out.println("Saving user object on table");
session.getTransaction().commit();
System.out.println("Transaction Commited!");
session.beginTransaction();
User loadedUser = session.get(User.class, 1);
System.out.println(loadedUser.getName());
System.out.println(loadedUser.getProteinData().getGoal());
System.out.println(loadedUser.getProteinData().getTotal());
loadedUser.getProteinData().setTotal(loadedUser.getProteinData().getTotal() + 50);
loadedUser.getHistory().add(new UserHistory(new Date(), "Added 50 Protein!"));
for (UserHistory history : loadedUser.getHistory()) {
System.out.println(history.getEntryTime().toString() + " " + history.getEntry());
}
session.getTransaction().commit();
session.close();
System.out.println("Session Closed!!!");
HibernateUtilities().getSessionFactory().close();
System.out.println("Session Factory Closed");
}
}
user class
package com.simpleProgrammer;
import java.util.HashSet;
import java.util.Set;
public class User {
private int id;
private String name;
private ProteinData proteinData = new ProteinData();
private Set<UserHistory> history = new HashSet<UserHistory>();
public Set<UserHistory> getHistory() {
return history;
}
public void setHistory(Set<UserHistory> history) {
this.history = history;
}
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 ProteinData getProteinData() {
return proteinData;
}
public void setProteinData(ProteinData proteinData) {
this.proteinData = proteinData;
}
}
here is my project structure
I think you should check your other configure file."Unknown entity" means your application doesn't find something like User.hbm.xml in the path.
I'm working for several hours on this issue about hibernate mapping. I think the error could be a simple syntax mistake but I can't find it!!!
I ran into the following exception when I executed my code:
Initial SessionFactory creation failed.org.hibernate.MappingException: entity class not found: LegalFee
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.plm.dao.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:33)
at com.plm.dao.util.HibernateUtil.getSessionFactory(HibernateUtil.java:39)
at com.plm.dao.AppTest.main(AppTest.java:15)
Firstly, I'm using hibernate 4.2 with Java 8 and MariaDB 10.
See all configurations below.
My hibernate.cfg.xml, I removed C3P0 configuration:
<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/PokerLeagueManager</property>
<property name='connection.username'>root</property>
<property name='connection.password'>mypassword</property>
<property name="show_sql">true</property>
<!-- SQL dialect -->
<property name='dialect'>org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</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>
<mapping resource="mappings/BlindStructure.hbm.xml"/>
<mapping resource="mappings/Tournament.hbm.xml"/>
<mapping resource="mappings/LegalFee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The error is on LegalFee bean so focus on it.
See the sql table creation of legalFee:
CREATE TABLE `legalFee` (
`idFee` int(11) NOT NULL,
`shortName` varchar(50) NOT NULL,
`description` varchar(200) DEFAULT NULL,
`feePercent` int(11) DEFAULT NULL,
`feeFixed` int(11) DEFAULT NULL,
PRIMARY KEY (`idFee`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The class :
public class LegalFee implements Serializable {
/**
* generated serial uid
*/
private static final long serialVersionUID = -2259355205530727294L;
private int idFee;
private String shortName;
private String description;
private Integer feePercent;
private Integer feeFixed;
private Set<Tournament> tournaments = new HashSet<Tournament>(0);
public LegalFee() {
}
public LegalFee(int idFee, String shortName) {
this.idFee = idFee;
this.shortName = shortName;
}
public LegalFee(int idFee, String shortName, String description,
Integer feePercent, Integer feeFixed, Set<Tournament> tournaments) {
this.idFee = idFee;
this.shortName = shortName;
this.description = description;
this.feePercent = feePercent;
this.feeFixed = feeFixed;
this.tournaments = tournaments;
}
public int getIdFee() {
return this.idFee;
}
public void setIdFee(int idFee) {
this.idFee = idFee;
}
public String getShortName() {
return this.shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getFeePercent() {
return this.feePercent;
}
public void setFeePercent(Integer feePercent) {
this.feePercent = feePercent;
}
public Integer getFeeFixed() {
return this.feeFixed;
}
public void setFeeFixed(Integer feeFixed) {
this.feeFixed = feeFixed;
}
public Set<Tournament> getTournaments() {
return this.tournaments;
}
public void setTournaments(Set<Tournament> tournaments) {
this.tournaments = tournaments;
}
}
And lastly the LegalFee.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="LegalFee" table="legalFee" catalog="PokerLeagueManager" optimistic-lock="version">
<id name="idFee" type="int">
<column name="idFee" />
<generator class="identity" />
</id>
<property name="shortName" type="string">
<column name="shortName" length="50" not-null="true" />
</property>
<property name="description" type="string">
<column name="description" length="200" />
</property>
<property name="feePercent" type="java.lang.Integer">
<column name="feePercent" />
</property>
<property name="feeFixed" type="java.lang.Integer">
<column name="feeFixed" />
</property>
<set name="tournaments" table="tournament" inverse="true" lazy="true" fetch="select">
<key>
<column name="legalFee_feeId" />
</key>
<one-to-many class="Tournament" />
</set>
</class>
</hibernate-mapping>
Thanks for your help.
If your LegalFee class is not in default package you need to provide the fully classified name of the class.
e.g "class name="com.abc.xyx.LegalFee" table="legalFee" "
I am using Hibernate4 with Spring and I am trying to map a Term class to a Document class. A term may occur in many documents and a document can contain many terms. I have read up on this, and I have attempted a number of fixes, including overriding the equals and hashCode methods.
In my database the terms and documents are stored in separated tables mediated by a relationship table. In the code here, it is called the jtable. I am using hibernates many-to-many mapping, but every time that I try to fetch a term object it simply deletes the row in the relationship table.
Here is a sample sql output that hibernate's show sql is giving out:
Hibernate: SELECT * FROM tags WHERE token='rose'
Hibernate: delete from jtable where tag_id=?
Here are the relevant classes and configs:
public class Term {
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Set<Document> getDocuments() {
return documents;
}
public void setDocuments(Set<Document> documents) {
documents = documents;
}
#Override
public boolean equals(Object obj) {
if(obj.getClass() != getClass()){
return false;
}
Term term = (Term) obj;
if (hashCode() == term.hashCode()){
return true;
}
return false;
}
#Override
public int hashCode(){
return word.hashCode();
}
private String word;
private int id;
private Set<Document> documents = new HashSet<Document>();
}
And the Document class :
public class Document implements Comparable<Document> {
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public URL getUrl() {
return url;
}
public void setUrl(URL url) {
this.url = url;
}
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
public Double getRank() {
return rank;
}
public void setRank(Double rank) {
this.rank = rank;
}
#Override
public boolean equals(Object obj) {
if(obj.getClass() != getClass()){
return false;
}
Document document = (Document) obj;
if (hashCode() == document.hashCode()){
return true;
}
return false;
}
#Override
public int hashCode(){
int hash = 1;
hash *= 1 + (length == null ? 0 :length);
hash *= 2 + (rank == null ? 0 :rank);
hash *= 3 + (title == null ? 0 : title.hashCode());
hash *= 4 + (url.hashCode());
return hash;
}
#Override
public int compareTo(Document document) {
return rank.compareTo(document.getRank());
}
private int id;
private Integer length;
private Double rank;
private String title;
private URL url;
}
Document.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="package.Document" table="documents">
<id name="id" type="java.lang.Integer">
<column name="document_id" />
<generator class="native" />
</id>
<property name="title" type="java.lang.String">
<column name="title" length="255" not-null="false" />
</property>
<property name="length">
<column name="length" not-null="false"/>
</property>
<property name="rank" type="java.lang.Double">
<column name="rank" not-null="false" />
</property>
<property name="url" type="org.hibernate.type.UrlType">
<column name="url" length="255" not-null="false" />
</property>
</class>
</hibernate-mapping>
Term.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="package.Term" table="tags">
<id name="id" type="java.lang.Integer">
<column name="tag_id" />
<generator class="native" />
</id>
<property name="word" type="string">
<column name="token" not-null="true" unique="true" />
</property>
<set name="documents" table="jtable"
inverse="false" lazy="true" fetch="select" cascade="all" >
<key>
<column name="tag_id" not-null="true" />
</key>
<many-to-many entity-name="package.Document">
<column name="document_id" not-null="true" />
</many-to-many>
</set>
</class>
</hibernate-mapping>
And the relevant context config section:
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.user}"/>
<property name="password" value="${database.password}"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>Document.hbm.xml</value>
<value>Term.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
I have been looking at this error for a while, so any answers would be appreciated.
What am I trying to do ?
While loading my project I get a weird exception:
rezg.admin.server.objects.common.pojo.EmailLogDetails, setter method of property: id
I am to save the object (persist) to the DB, using postgres. Environment is Java 6 , Hibernate 3 in Jboss 4 Environment. The jar contains "EmailLogDetails" is in the Jboss lib folder.
expected type: java.lang.Integer, actual value: java.lang.Integer IllegalArgumentException in class:
rezg.admin.server.objects.common.pojo.EmailLogDetails, setter method
of property: id
org.hibernate.PropertyAccessException: IllegalArgumentException
occurred while calling setter of
rezg.admin.server.objects.common.pojo.EmailLogDetails.Id at
org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:104)
at
org.hibernate.tuple.AbstractEntityTuplizer.setIdentifier(AbstractEntityTuplizer.java:204)
at
org.hibernate.persister.entity.AbstractEntityPersister.setIdentifier(AbstractEntityPersister.java:3261)
at
org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:157)
at
org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:114).....
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class 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:601) at
org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:42)
... 74 more
EmailLogDetails:
public class EmailLogDetails implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private java.lang.Integer id;
private String reservationNo;
private String mailSubject;
private String fromAddress;
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public java.lang.Integer getId() {
return id;
}
public void setId(java.lang.Integer id) {
this.id = id;
}
public String getMailSubject() {
return mailSubject;
}
public void setMailSubject(String mailSubject) {
this.mailSubject = mailSubject;
}
public String getMailType() {
return mailType;
}
}
XML
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"../server/default/conf/hibernate-mapping-3.0.dtd">
<hibernate-mapping auto-import="false" schema="##portalname##_admin">
<class name="rezg.admin.server.objects.common.pojo.EmailLogDetails" table="emaillogdetails">
<id name="Id" column="id" type="java.lang.Integer">
<generator class="sequence">
<param name="sequence">##portalname##_admin.seq_emaillogdetails</param>
</generator>
</id>
<property name="reservationNo" type="java.lang.String" >
<column name="reservationno" length="20" not-null="false" sql-type="varchar" />
</property>
<property name="mailSubject" type="java.lang.String" >
<column name="mailsubject" length="500" not-null="false" sql-type="varchar" />
</property>
By the looks of it you are missing the default constructor. Hibernate looks for the default constructor to create instances before playing around with import and export of mapping information between DB and class.
This is my first post in stackoverflow:
I am new to hibernate, infact below is my first code in hibernate:
i am repetedly getting "could not parse mapping document" error, when i run my main class.
below is the code for your refernce, please help me out of this.
Config 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.dialect">org.hibernate.dialect.DerbyDialect</property>
<property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
<property name="hibernate.connection.url">jdbc:derby://localhost:1527/sample</property>
<property name="hibernate.connection.username">one</property>
<property name="hibernate.connection.password">two</property>
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="EmployeeMapping.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Mapping file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Employee" table="EMPLOYEE"/>
<id name="emp_id" type="int" column="emp_id"/>
<property name="emp_name">
<column name="emp_name"/>
</property>
<property name="emp_branch">
<column name="emp_branch"/>
</property>
<property name="emp_Salary">
<column name="emp_salary"/>
</property>
<property name="emp_fav_dgt">
<column name="emp_fav_dgt"/>
</property>
</hibernate-mapping>
Pojo class:
public class Employee {
private int emp_id;
private String emp_name;
private String emp_branch;
private int emp_Salary;
private int emp_fav_dgt;
public int getEmp_Salary() {
return emp_Salary;
}
public void setEmp_Salary(int emp_Salary) {
this.emp_Salary = emp_Salary;
}
public String getEmp_branch() {
return emp_branch;
}
public void setEmp_branch(String emp_branch) {
this.emp_branch = emp_branch;
}
public int getEmp_fav_dgt() {
return emp_fav_dgt;
}
public void setEmp_fav_dgt(int emp_fav_dgt) {
this.emp_fav_dgt = emp_fav_dgt;
}
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
public String getEmp_name() {
return emp_name;
}
public void setEmp_name(String emp_name) {
this.emp_name = emp_name;
}
}
Main class:
public class Main {
public static void main(String[] args) {
System.out.println("asdf");
SessionFactory sessionFactory = null;
Transaction ts = null;
Session session = null;
Configuration conf = null;
try{
conf = new org.hibernate.cfg.Configuration().configure();
sessionFactory = conf.buildSessionFactory();
session =sessionFactory.openSession();
Employee customer = new Employee();
customer.setEmp_id(1);
customer.setEmp_name("one");
customer.setEmp_branch("old");
customer.setEmp_Salary(1000);
customer.setEmp_fav_dgt(2);
session.save(customer);
ts.commit();
}
catch(Exception e){
e.printStackTrace();;
}
finally{
session.close();
}
}
}
The property tags corresponding with the fields should be nested within the class tag.
<class name="Employee" table="EMPLOYEE">
<id name="emp_id" type="int" column="emp_id"/>
<property name="emp_name">
<column name="emp_name"/>
</property>
<property name="emp_branch">
<column name="emp_branch"/>
</property>
<property name="emp_Salary">
<column name="emp_salary"/>
</property>
<property name="emp_fav_dgt">
<column name="emp_fav_dgt"/>
</property>
</class>