I have done an example for login using database in hibernate.My Xml and entity classes are
User.java:
import java.util.Date;
import javax.persistence.Entity;
#Entity(name="User")
public class User {
private Integer userID;
private String username;
private String password;
private Date createdDate;
/**
* Default Constructor
*/
public User() {
super();
}
public User(Integer userID, String username, String password) {
this.userID = userID;
this.username = username;
this.password = password;
}
public Integer getUserID() {
return userID;
}
public void setUserID(Integer userID) {
this.userID = userID;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
}//end of class()
UserBooks.java:
public class UsersBooks {
// Declaring all attributes
private double userID;
private String bookID;
private String permission;
// Constructors
public UsersBooks() {
super();
}
public UsersBooks(double userID, String bookID, String permission) {
super();
this.userID = userID;
this.bookID = bookID;
this.permission = permission;
}
// Getters and Setters
public double getUserID() {
return userID;
}
public void setUserID(double userID) {
this.userID = userID;
}
public String getBookID() {
return bookID;
}
public void setBookID(String bookID) {
this.bookID = bookID;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
// Overriding toString()
#Override
public String toString() {
return "UsersBooks [userID=" + userID + ", bookID=" + bookID
+ ", permission=" + permission + "]";
}//end of toString()
}//end of class
UserSocialInfo.java:
public class UserSocialInfo {
private int socialID;
private String loginProvider;
private String loginProviderUID;
private String UID;
private String nickname;
private String photoURL;
private String thumbnailURL;
private int birthDay;
private int birthMonth;
private int birthYear;
private String gender;
private String proxiedEmail;
private String country;
private String state;
private String city;
private String zip;
private String firstname;
private String lastname;
private String profileURL;
private int userID;
/**
*
*/
public UserSocialInfo() {
// TODO Auto-generated constructor stub
}
/**
* #return the socialID
*/
public int getSocialID() {
return socialID;
}
/**
* #param socialID the socialID to set
*/
public void setSocialID(int socialID) {
this.socialID = socialID;
}
/**
* #return the loginProvider
*/
public String getLoginProvider() {
return loginProvider;
}
/**
* #param loginProvider the loginProvider to set
*/
public void setLoginProvider(String loginProvider) {
this.loginProvider = loginProvider;
}
/**
* #return the loginProviderUID
*/
public String getLoginProviderUID() {
return loginProviderUID;
}
/**
* #param loginProviderUID the loginProviderUID to set
*/
public void setLoginProviderUID(String loginProviderUID) {
this.loginProviderUID = loginProviderUID;
}
/**
* #return the uID
*/
public String getUID() {
return UID;
}
/**
* #param uID the uID to set
*/
public void setUID(String uID) {
UID = uID;
}
/**
* #return the nickname
*/
public String getNickname() {
return nickname;
}
/**
* #param nickname the nickname to set
*/
public void setNickname(String nickname) {
this.nickname = nickname;
}
/**
* #return the photoURL
*/
public String getPhotoURL() {
return photoURL;
}
/**
* #param photoURL the photoURL to set
*/
public void setPhotoURL(String photoURL) {
this.photoURL = photoURL;
}
/**
* #return the thumbnailURL
*/
public String getThumbnailURL() {
return thumbnailURL;
}
/**
* #param thumbnailURL the thumbnailURL to set
*/
public void setThumbnailURL(String thumbnailURL) {
this.thumbnailURL = thumbnailURL;
}
/**
* #return the birthDay
*/
public int getBirthDay() {
return birthDay;
}
/**
* #param birthDay the birthDay to set
*/
public void setBirthDay(int birthDay) {
this.birthDay = birthDay;
}
/**
* #return the birthMonth
*/
public int getBirthMonth() {
return birthMonth;
}
/**
* #param birthMonth the birthMonth to set
*/
public void setBirthMonth(int birthMonth) {
this.birthMonth = birthMonth;
}
/**
* #return the birthYear
*/
public int getBirthYear() {
return birthYear;
}
/**
* #param birthYear the birthYear to set
*/
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}
/**
* #return the gender
*/
public String getGender() {
return gender;
}
/**
* #param gender the gender to set
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
* #return the proxiedEmail
*/
public String getProxiedEmail() {
return proxiedEmail;
}
/**
* #param proxiedEmail the proxiedEmail to set
*/
public void setProxiedEmail(String proxiedEmail) {
this.proxiedEmail = proxiedEmail;
}
/**
* #return the country
*/
public String getCountry() {
return country;
}
/**
* #param country the country to set
*/
public void setCountry(String country) {
this.country = country;
}
/**
* #return the state
*/
public String getState() {
return state;
}
/**
* #param state the state to set
*/
public void setState(String state) {
this.state = state;
}
/**
* #return the city
*/
public String getCity() {
return city;
}
/**
* #param city the city to set
*/
public void setCity(String city) {
this.city = city;
}
/**
* #return the zip
*/
public String getZip() {
return zip;
}
/**
* #param zip the zip to set
*/
public void setZip(String zip) {
this.zip = zip;
}
/**
* #return the firstname
*/
public String getFirstname() {
return firstname;
}
/**
* #param firstname the firstname to set
*/
public void setFirstname(String firstname) {
this.firstname = firstname;
}
/**
* #return the lastname
*/
public String getLastname() {
return lastname;
}
/**
* #param lastname the lastname to set
*/
public void setLastname(String lastname) {
this.lastname = lastname;
}
/**
* #return the profileURL
*/
public String getProfileURL() {
return profileURL;
}
/**
* #param profileURL the profileURL to set
*/
public void setProfileURL(String profileURL) {
this.profileURL = profileURL;
}
/**
* #return the userID
*/
public int getUserID() {
return userID;
}
/**
* #param userID the userID to set
*/
public void setUserID(int userID) {
this.userID = userID;
}
}
My xml files
User.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.entities.User" table="users">
<id name="userID" type="long" column="userid">
<generator class="increment" />
</id>
<property name="username" column="username" />
<property name="password" column="password" />
<property name="userID" column="userid" insert="false" update="false"/>
<property name="createdDate" column="created_date" />
</class>
</hibernate-mapping>
UserBooks.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.entities.UsersBooks" table="users_books">
<id name="userID" type="long" column="user_id">
</id>
<property name="userID" column="user_id" insert="false" update="false"/>
<property name="bookID" column="book_id" insert="false" update="false"/>
<property name="permission" column="permissions" />
</class>
</hibernate-mapping>
UserSocialInfo.java:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.entities.UserSocialInfo" table="user_social_info">
<id name="socialID" type="long" column="social_id">
<generator class="increment" />
</id>
<property name="socialID" column="social_id" insert="false" update="false"/>
<property name="loginProvider" column="login_provider" />
<property name="loginProviderUID" column="login_provider_uid" insert="false" update="false"/>
<property name="UID" column="uid" insert="false" update="false"/>
<property name="nickname" column="nickname" />
<property name="photoURL" column="photo_url" />
<property name="thumbnailURL" column="thumbnail_url" />
<property name="birthDay" column="birthday" />
<property name="birthMonth" column="birthmonth" />
<property name="birthYear" column="birthyear" />
<property name="gender" column="gender" />
<property name="proxiedEmail" column="proxied_email" />
<property name="country" column="country" />
<property name="state" column="state" />
<property name="city" column="city" />
<property name="zip" column="zip" />
<property name="firstname" column="firstname" />
<property name="lastname" column="lastname" />
<property name="profileURL" column="profile_url" />
<property name="userID" column="user_id" insert="false" update="false"/>
</class>
</hibernate-mapping>
hibernate.cfg.xml:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="fabulaFactory">
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/appname
</property>
<property name="connection.username">
user
</property>
<property name="connection.password">
pwd
</property>
<property name="connection.pool_size">5</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.MySQLInnoDBDialect
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="com//hibernatexmlfiles//User.hbm.xml"/>
<mapping resource="com//hibernatexmlfiles//UsersBooks.hbm.xml"/>
<mapping resource="com//hibernatexmlfiles//UserSocialInfo.hbm.xml"/>
</session-factory>
</hibernate-configuration>
While executing the project i am getting an error like this:
org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of com.fabulait.fabula.entities.User.userID
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:70)
at org.hibernate.tuple.AbstractTuplizer.setIdentifier(AbstractTuplizer.java:130)
at org.hibernate.persister.entity.BasicEntityPersister.setIdentifier(BasicEntityPersister.java:2930)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:146)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:184)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:173)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:69)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:477)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:472)
at com.service.UserService.storeSessionInfo(UserService.java:410)
at com.web.LoginUser.doPost(LoginUser.java:122)
at com.web.LoginUser.doGet(LoginUser.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:679)
Caused by: java.lang.IllegalArgumentException: argument type mismatch
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:616)
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:40)
... 32 more
So please give suggestions.
It should be
from User u where u.username=:username
I assume User is the entity class (#Entity) mapped with table
Also, keep in mind if you have turned auto-import to "false", you'll need to either fully qualify the classname, or set name
#Entity(name="User")
public class User {
}
As a suggestion, for most simpler queries, it's usually easier (and more performant since you don't have to parse the hql to an AST tree) to use criteria queries. And in your case, you're just checking for any match. So iterating through the results to compare the username is redundant to what is in your where clause. The following is a much more efficient way to do what you're looking for:
Criteria c = session.createCriteria(User.class);
c.add(Restrictions.eq("username", username));
c.setProjection(Projections.rowCount());
Number count = (Number) c.uniqueResult();
return (count.intValue() > 0);
Related
I'm calling createSession method in Main method.
private static void createSession() {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory = meta.getSessionFactoryBuilder().build();
Session session = factory.openSession();
Transaction t = session.beginTransaction();
SessionFactory fact = meta.getSessionFactoryBuilder().build();
Session ss = factory.openSession();
Transaction tt = session.beginTransaction();
BatchJobConfig config = new BatchJobConfig();
BatchJobConfigDetails details = new BatchJobConfigDetails();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
System.out.println("timestamp -> "+timestamp);
BatchJobConfigDetails batchJobConfigDtl = new BatchJobConfigDetails(300, 3, "JAVA", date, "JAVA", date, "N",
"Some Key", "Some value", "FT", "KEY DESCRIPTION", "Y");
try {
config.setBatchJobConfigDtl(batchJobConfigDtl);
config.setAddUserCd("gdfdgdfgdgd");
config.setBatchJobConfigId(505);
config.setActiveInd("YYYY");
config.setAddUserDtm(timestamp);
config.setDeleteInd("N");
config.setEndDtm(timestamp);
config.setJobDesc("DESCRIPTION");
config.setJobNm("JOB NAME");
config.setJobType("Job Type");
config.setLastUpdtDtm(timestamp);
config.setLastUpdtUserCd("someone");
config.setStatus("COMPLETED");
config.setStartDtm(timestamp);
ss.save(config);
tt.commit();
System.out.println("config session saved");
} catch (HibernateException exception) {
System.out.println("Problem creating session factory!!!!!!!!!!");
exception.printStackTrace();
} finally {
fact.close();
ss.close();
}
try {
details.setAddUserCd("fffffffffffffffffffff");
details.setAddUserDtm(timestamp);
details.setBusinessUpdtInd("dssssssss");
details.setDeleteInd("NNNNNNNNN");
details.setKeyDataType("ggggggggggggg");
details.setKeyDesc("Description.......");
details.setKeyNm("some key name");
details.setKeyVal("someval");
details.setLastUpdtDtm(timestamp);
details.setLastUpdtUserCd("last user");
BatchJobConfig batchJobConfig = new BatchJobConfig(1L, "JAVA", date, "C#", date, "N", "MissingCK",
"JOB DESCRIPTION", "FT", date, date, "COMPLETED", "Y");
List<BatchJobConfig> b = null;
b.add(batchJobConfig);
details.setBatchJobConfigs(b);
session.save(details);
t.commit();
System.out.println("details session saved");
} catch (HibernateException exception) {
System.out.println("Problem creating session factory....");
exception.printStackTrace();
} finally {
factory.close();
session.close();
}
}
I have the following two Entities.
BatchJobConfig.java
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import javax.persistence.*;
/**
* The persistent class for the BATCH_JOB_CONFIG database table.
*
*/
#Entity
#Table(name="BATCH_JOB_CONFIG")
#NamedQuery(name="BatchJobConfig.findAll", query="SELECT b FROM BatchJobConfig b")
public class BatchJobConfig implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="BATCH_JOB_CONFIG_ID")
private long batchJobConfigId;
#Column(name="ADD_USER_CD")
private String addUserCd;
#Column(name="ADD_USER_DTM")
private Timestamp addUserDtm;
#Column(name="LAST_UPDT_USER_CD")
private String lastUpdtUserCd;
#Column(name="LAST_UPDT_DTM")
private Timestamp lastUpdtDtm;
#Column(name="DELETE_IND")
private String deleteInd;
#Column(name="JOB_NM")
private String jobNm;
#Column(name="JOB_DESC")
private String jobDesc;
#Column(name="JOB_TYPE")
private String jobType;
#Column(name="START_DTM")
private Timestamp startDtm;
#Column(name="END_DTM")
private Timestamp endDtm;
#Column(name="STATUS")
private String status;
#Column(name="ACTIVE_IND")
private String activeInd;
public Timestamp getAddUserDtm() {
return addUserDtm;
}
public void setAddUserDtm(Timestamp addUserDtm) {
this.addUserDtm = addUserDtm;
}
public String getLastUpdtUserCd() {
return lastUpdtUserCd;
}
public void setLastUpdtUserCd(String lastUpdtUserCd) {
this.lastUpdtUserCd = lastUpdtUserCd;
}
public Timestamp getLastUpdtDtm() {
return lastUpdtDtm;
}
public void setLastUpdtDtm(Timestamp lastUpdtDtm) {
this.lastUpdtDtm = lastUpdtDtm;
}
public String getDeleteInd() {
return deleteInd;
}
public void setDeleteInd(String deleteInd) {
this.deleteInd = deleteInd;
}
public String getJobNm() {
return jobNm;
}
public void setJobNm(String jobNm) {
this.jobNm = jobNm;
}
public String getJobDesc() {
return jobDesc;
}
public void setJobDesc(String jobDesc) {
this.jobDesc = jobDesc;
}
public String getJobType() {
return jobType;
}
public void setJobType(String jobType) {
this.jobType = jobType;
}
public Timestamp getStartDtm() {
return startDtm;
}
public void setStartDtm(Timestamp startDtm) {
this.startDtm = startDtm;
}
public Timestamp getEndDtm() {
return endDtm;
}
public void setEndDtm(Timestamp endDtm) {
this.endDtm = endDtm;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getActiveInd() {
return activeInd;
}
public void setActiveInd(String activeInd) {
this.activeInd = activeInd;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
//bi-directional many-to-one association to BatchJobConfigDtl
#ManyToOne
#JoinColumn(name="BATCH_JOB_CONFIG_ID", referencedColumnName="BATCH_JOB_CONFIG_ID")
private BatchJobConfigDetails batchJobConfigDtl;
public BatchJobConfig() {
}
public BatchJobConfig(long l, String string, Date date, String string2, Date date2, String string3, String string4,
String string5, String string6, Date date3, Date date4, String string7, String string8) {
// TODO Auto-generated constructor stub
}
public long getBatchJobConfigId() {
return this.batchJobConfigId;
}
public void setBatchJobConfigId(long batchJobConfigId) {
this.batchJobConfigId = batchJobConfigId;
}
public String getAddUserCd() {
return this.addUserCd;
}
public void setAddUserCd(String addUserCd) {
this.addUserCd = addUserCd;
}
public BatchJobConfigDetails getBatchJobConfigDtl() {
return this.batchJobConfigDtl;
}
public void setBatchJobConfigDtl(BatchJobConfigDetails batchJobConfigDtl) {
this.batchJobConfigDtl = batchJobConfigDtl;
}
}
BatchJobConfigDetails.java
import java.io.Serializable;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
/**
* The persistent class for the BATCH_JOB_CONFIG_DTLS database table.
*
*/
#Entity
#Table(name = "BATCH_JOB_CONFIG_DTLS")
#NamedQuery(name = "BatchJobConfigDtl.findAll", query = "SELECT b FROM BatchJobConfigDtl b")
public class BatchJobConfigDetails implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "BATCH_JOB_CONFIG_DTLS_ID")
private long batchJobConfigDtlsId;
#Column(name = "ADD_USER_CD")
private String addUserCd;
#Column(name = "ADD_USER_DTM")
private Timestamp addUserDtm;
#Column(name = "BUSINESS_UPDT_IND")
private String businessUpdtInd;
#Column(name = "DELETE_IND")
private String deleteInd;
#Column(name = "KEY_DATA_TYPE")
private String keyDataType;
#Column(name = "KEY_DESC")
private String keyDesc;
#Column(name = "KEY_NM")
private String keyNm;
#Column(name = "KEY_VAL")
private String keyVal;
#Column(name = "LAST_UPDT_DTM")
private Timestamp lastUpdtDtm;
#Column(name = "LAST_UPDT_USER_CD")
private String lastUpdtUserCd;
// bi-directional many-to-one association to BatchJobConfig
#OneToMany(mappedBy = "batchJobConfigDtl")
private List<BatchJobConfig> batchJobConfigs;
public BatchJobConfigDetails() {
}
public BatchJobConfigDetails(int i, int j, String string, Date date, String string2, Date date2, String string3,
String string4, String string5, String string6, String string7, String string8) {
// TODO Auto-generated constructor stub
}
public BatchJobConfigDetails(int i, BatchJobConfig config1, String string, Date date, String string2, Date date2,
String string3, String string4, String string5, String string6, String string7, String string8) {
// TODO Auto-generated constructor stub
}
public long getBatchJobConfigDtlsId() {
return this.batchJobConfigDtlsId;
}
public void setBatchJobConfigDtlsId(long batchJobConfigDtlsId) {
this.batchJobConfigDtlsId = batchJobConfigDtlsId;
}
public String getAddUserCd() {
return this.addUserCd;
}
public void setAddUserCd(String addUserCd) {
this.addUserCd = addUserCd;
}
public Timestamp getAddUserDtm() {
return this.addUserDtm;
}
public void setAddUserDtm(Timestamp addUserDtm) {
this.addUserDtm = addUserDtm;
}
public String getBusinessUpdtInd() {
return this.businessUpdtInd;
}
public void setBusinessUpdtInd(String businessUpdtInd) {
this.businessUpdtInd = businessUpdtInd;
}
public String getDeleteInd() {
return this.deleteInd;
}
public void setDeleteInd(String deleteInd) {
this.deleteInd = deleteInd;
}
public String getKeyDataType() {
return this.keyDataType;
}
public void setKeyDataType(String keyDataType) {
this.keyDataType = keyDataType;
}
public String getKeyDesc() {
return this.keyDesc;
}
public void setKeyDesc(String keyDesc) {
this.keyDesc = keyDesc;
}
public String getKeyNm() {
return this.keyNm;
}
public void setKeyNm(String keyNm) {
this.keyNm = keyNm;
}
public String getKeyVal() {
return this.keyVal;
}
public void setKeyVal(String keyVal) {
this.keyVal = keyVal;
}
public Timestamp getLastUpdtDtm() {
return this.lastUpdtDtm;
}
public void setLastUpdtDtm(Timestamp lastUpdtDtm) {
this.lastUpdtDtm = lastUpdtDtm;
}
public String getLastUpdtUserCd() {
return this.lastUpdtUserCd;
}
public void setLastUpdtUserCd(String lastUpdtUserCd) {
this.lastUpdtUserCd = lastUpdtUserCd;
}
public List<BatchJobConfig> getBatchJobConfigs() {
return this.batchJobConfigs;
}
public void setBatchJobConfigs(List<BatchJobConfig> batchJobConfigs) {
this.batchJobConfigs = batchJobConfigs;
}
public BatchJobConfig addBatchJobConfig(BatchJobConfig batchJobConfig) {
getBatchJobConfigs().add(batchJobConfig);
batchJobConfig.setBatchJobConfigDtl(this);
return batchJobConfig;
}
public BatchJobConfig removeBatchJobConfig(BatchJobConfig batchJobConfig) {
getBatchJobConfigs().remove(batchJobConfig);
batchJobConfig.setBatchJobConfigDtl(null);
return batchJobConfig;
}
}
batchJob.hbm.xml
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="BatchJobConfig" table="BATCH_JOB_CONFIG">
<meta attribute="class-description">
This class contains the BATCH_JOB_CONFIG.
</meta>
<id name="batchJobConfigId" type="int" column="BATCH_JOB_CONFIG_ID">
<generator class="native" />
</id>
<property name="addUserCd" column="ADD_USER_CD" type="string" />
<property name="addUserDtm" column="ADD_USER_DTM" type="timestamp" />
<property name="lastUpdtUserCd" column="LAST_UPDT_USER_CD"
type="string" />
<property name="lastUpdtDtm" column="LAST_UPDT_DTM" type="timestamp" />
<property name="deleteInd" column="DELETE_IND" type="string" />
<property name="jobNm" column="JOB_NM" type="string" />
<property name="jobDesc" column="JOB_DESC" type="string" />
<property name="jobType" column="JOB_TYPE" type="string" />
<property name="startDtm" column="START_DTM" type="timestamp" />
<property name="status" column="STATUS" type="string" />
<property name="endDtm" column="END_DTM" type="timestamp" />
<property name="activeInd" column="ACTIVE_IND" type="string" />
<many-to-one name="BatchJobConfigDetails" column="BATCH_JOB_CONFIG_ID"
class="BatchJobConfigDetails" not-null="true" />
</class>
<class name="BatchJobConfigDetails" table="BATCH_JOB_CONFIG_DTLS">
<meta attribute="class-description">
This class contains the BATCH_JOB_CONFIG_DETAILS.
</meta>
<id name="batchJobConfigDtlsId" type="int" column="BATCH_JOB_CONFIG_DTLS_ID">
<generator class="native" />
</id>
<property name="batchJobConfigId" column="BATCH_JOB_CONFIG_ID"
type="int" />
<property name="addUserCd" column="ADD_USER_CD" type="string" />
<property name="addUserDtm" column="ADD_USER_DTM" type="timestamp" />
<property name="businessUpdtInd" column="BUSINESS_UPDT_IND"
type="int" />
<property name="deleteInd" column="DELETE_IND" type="string" />
<property name="keyDataType" column="KEY_DATA_TYPE" type="string" />
<property name="keyDesc" column="KEY_DESC" type="string" />
<property name="keyNm" column="KEY_NM" type="string" />
<property name="keyVal" column="KEY_VAL" type="string" />
<property name="lastUpdtDtm" column="LAST_UPDT_DTM" type="timestamp" />
<property name="lastUpdtUserCd" column="LAST_UPDT_USER_CD" type="string" />
</class>
</hibernate-mapping>
hibernate.cfg.xml
<!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.DB2Dialect</property>
<property name="hibernate.connection.driver_class">com.ibm.db2.jcc.DB2Driver</property>
<property name="hibernate.connection.url">jdbc:db2://sdfsfsd:5000df2/dsf</property>
<property name="hibernate.connection.username">sfs</property>
<property name="hibernate.connection.password">sfs</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<mapping resource="batchJob.hbm.xml"/>
</session-factory>
</hibernate-configuration>
What does it mean by this error message and how do you solve it?
Exception in thread "main" org.hibernate.MappingException: Repeated column in mapping for entity: BatchJobConfig column: BATCH_JOB_CONFIG_ID (should be mapped with insert="false" update="false")
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:862)
at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:880)
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:902)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:634)
at org.hibernate.mapping.RootClass.validate(RootClass.java:267)
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:347)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:466)
at com.hms.api.batch.job.config.StartBatchJobConfigApplication.createSession(StartBatchJobConfigApplication.java:67)
at com.hms.api.batch.job.config.StartBatchJobConfigApplication.main(StartBatchJobConfigApplication.java:34)
What does this error message mean?
if yes how did you resolve it? Please help me with issue.
I appreciate your responses in advance. Thank you!!!!!!!!!!!!!!
In your java code, change a name of many to one relation, to anything but the current:
#ManyToOne
#JoinColumn(name="BATCH_JOB_CONFIG_ID", referencedColumnName="BATCH_JOB_CONFIG_ID")
private BatchJobConfigDetails batchJobConfigDtl;
something like
#ManyToOne
#JoinColumn(name="MY_NEW_NAME", referencedColumnName="BATCH_JOB_CONFIG_ID")
private BatchJobConfigDetails batchJobConfigDtl;
and also change it in your hbm.xml file appropriately.
UPDATE:
Also, change a name of columns in your hbl.xml file. One second.
from
<many-to-one name="BatchJobConfigDetails" column="BATCH_JOB_CONFIG_ID"
class="BatchJobConfigDetails" not-null="true" />
to
<many-to-one name="BatchJobConfigDetails" column="MY_NEW_NAME"
class="BatchJobConfigDetails" not-null="true" />
I have a POJO class NewUniversity.java. I've created a mapping file for it viz. RegisterAction.hbm.xml. Now the problem is when I try to call the save methods from DAO class, only the first one gets executed, the second one doesn't. I've two tables linked to one entity through 'entity-mapping' attribute in the xml file.
File: NewUniversity.java
public class NewUniversity implements Serializable {
// University fields
private String uCode;
private String uName;
private String uAddress;
private String uCity;
private String uState;
private long uContactNo;
private String uEmail;
// University director fields
private String name;
private String address;
private String city;
private String state;
private long contactNo;
private String email;
private String userName;
private String pwd;
public String getuCode() {
return uCode;
}
public void setuCode(String uCode) {
this.uCode = uCode;
}
public String getuName() {
return uName;
}
public void setuName(String uName) {
this.uName = uName;
}
public String getuAddress() {
return uAddress;
}
public void setuAddress(String uAddress) {
this.uAddress = uAddress;
}
public String getuCity() {
return uCity;
}
public void setuCity(String uCity) {
this.uCity = uCity;
}
public String getuState() {
return uState;
}
public void setuState(String uState) {
this.uState = uState;
}
public long getuContactNo() {
return uContactNo;
}
public void setuContactNo(long uContactNo) {
this.uContactNo = uContactNo;
}
public String getuEmail() {
return uEmail;
}
public void setuEmail(String uEmail) {
this.uEmail = uEmail;
}
// University directors setters/getters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
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 long getContactNo() {
return contactNo;
}
public void setContactNo(long contactNo) {
this.contactNo = contactNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
File: RegisterAction.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="in.ryr.register.NewUniversity" table="university"
entity-name="university">
<id name="uCode" column="code" type="string">
<generator class="assigned" />
</id>
<property name="uName" column="name" />
<property name="uAddress" column="address" />
<property name="uCity" column="city" />
<property name="uState" column="state" />
<property name="uContactNo" column="contact_no" />
<property name="uEmail" column="email" />
<property name="userName" column="username" />
</class>
<class name="in.ryr.register.NewUniversity" table="university_director"
entity-name="uniDirector">
<id name="userName" column="username" type="string">
<generator class="assigned" />
</id>
<property name="name" column="name" />
<property name="address" column="address" />
<property name="city" column="city" />
<property name="state" column="state" />
<property name="contactNo" column="contact_no" />
<property name="email" column="email" />
<property name="pwd" column="password" />
<property name="uCode" column="u_code" />
</class>
</hibernate-mapping>
File: RegisterDAO.java
public void register(NewUniversity user) throws Exception {
session = factory.openSession();
transaction = session.beginTransaction();
try {
session.save("university", user); //This is working fine
session.save("uniDirector", user); //This doesn't execute at all
transaction.commit();
session.close();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
session.close();
}
}
I've tried using persist() as well. But no luck!
The point is, when I perform it on two different sessions, it works perfectly. (All the objects value are coming through .jsp to struts). For some reasons I didn't use annotations.
Maybe it is because Session#save(entityName, object) method requires object to be a "transient" object (i.e. that has not already been persisted), and that, after the first call to session.save("university", user); then user is no more transient.
Persist the given transient instance, first assigning a generated
identifier. (Or using the current value of the identifier property if
the assigned generator is used.) This operation cascades to associated
instances if the association is mapped with cascade="save-update"
What happens when you make a get of your persisted "university" entity just after the first save, and then save it as "uniDirector" ?
Hai all I am using hibernate and Microsoft SQL server.
I have a view in my database as follows
create view [dbo].[Pat_Det] As Select patientid As pid,title, fname, mname,lname,dob,gender,mstatus,idtype,idno,mtongue,emailid,smsstatus,mailstatus,status,regcenter,regdate from dbo.LAB_patientreg WHERE 1=1
For this view I had created a Pojo class like this
package POJO;
import java.io.Serializable;
import java.util.Date;
public class AddressViewPojo implements Serializable{
String pid, title, fname, mname, lname, sex, mstatus, idtype, aadhar_no, emailid, regcenter;
Date dob, date_created;
int allow_sms, allow_email, status;
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getMname() {
return mname;
}
public void setMname(String mname) {
this.mname = mname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getMstatus() {
return mstatus;
}
public void setMstatus(String mstatus) {
this.mstatus = mstatus;
}
public String getIdtype() {
return idtype;
}
public void setIdtype(String idtype) {
this.idtype = idtype;
}
public String getAadhar_no() {
return aadhar_no;
}
public void setAadhar_no(String aadhar_no) {
this.aadhar_no = aadhar_no;
}
public String getEmailid() {
return emailid;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public String getRegcenter() {
return regcenter;
}
public void setRegcenter(String regcenter) {
this.regcenter = regcenter;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
public int getAllow_sms() {
return allow_sms;
}
public void setAllow_sms(int allow_sms) {
this.allow_sms = allow_sms;
}
public int getAllow_email() {
return allow_email;
}
public void setAllow_email(int allow_email) {
this.allow_email = allow_email;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
and Mapping file like this
<?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 auto-import="true" default-lazy="false">
<class name="POJO.AddressViewPojo" table="Pat_Det">
<property name="aadhar_no" column="aadhar_no"></property>
<property name="allow_email" column="allow_email"></property>
<property name="allow_sms" column="allow_sms"></property>
<property name="date_created" column="date_created"></property>
<property name="dob" column="dob"></property>
<property name="emailid" column="emailid"></property>
<property name="fname" column="emailid"></property>
<property name="idtype" column="idtype"></property>
<property name="lname" column="lname"></property>
<property name="mname" column="mname"></property>
<property name="mstatus" column="mstatus"></property>
<property name="pid" column="pid"></property>
<property name="regcenter" column="regcenter"></property>
<property name="sex" column="sex"></property>
<property name="status" column="status"></property>
<property name="title" column="title"></property>
</class>
</hibernate-mapping>
But when I am validating the Mapping file an error occurs like this
XML validation started.
Checking file:/E:/akshai/TREVALAB/src/MAPPING/AddressViewPojo.hbm.xml...
The content of element type "class" must match "(meta*,subselect?,cache?,synchronize*,comment?,tuplizer*,(id|composite-id),discriminator?,natural-id?,(version|timestamp)?,(property|many-to-one|one-to-one|component|dynamic-component|properties|any|map|set|list|bag|idbag|array|primitive-array)*,((join*,subclass*)|joined-subclass*|union-subclass*),loader?,sql-insert?,sql-update?,sql-delete?,filter*,resultset*,(query|sql-query)*)". [21]
XML validation finished.
Can anyone help me to solve out this issue.
Thanks in advance.
Your mapping absolutely needs an id. I guess PID is your id so you should write something like this :
<?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 auto-import="true" default-lazy="false">
<class name="POJO.AddressViewPojo" table="Pat_Det">
<id name="pid" column="pid"></id> <!-- Right here -->
<property name="aadhar_no" column="aadhar_no"></property>
<property name="allow_email" column="allow_email"></property>
<property name="allow_sms" column="allow_sms"></property>
<property name="date_created" column="date_created"></property>
<property name="dob" column="dob"></property>
<property name="emailid" column="emailid"></property>
<property name="fname" column="emailid"></property>
<property name="idtype" column="idtype"></property>
<property name="lname" column="lname"></property>
<property name="mname" column="mname"></property>
<property name="mstatus" column="mstatus"></property>
<property name="regcenter" column="regcenter"></property>
<property name="sex" column="sex"></property>
<property name="status" column="status"></property>
<property name="title" column="title"></property>
</class>
</hibernate-mapping>
I have three classes
Student.java
public class Student {
long id;
String name;
Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
Address.java
public class Address {
String houseNumber;
String addrLine1;
String addrLine2;
String phone;
public String getHouseNumber() {
return houseNumber;
}
public void setHouseNumber(String houseNumber) {
this.houseNumber = houseNumber;
}
public String getAddrLine1() {
return addrLine1;
}
public void setAddrLine1(String addrLine1) {
this.addrLine1 = addrLine1;
}
public String getAddrLine2() {
return addrLine2;
}
public void setAddrLine2(String addrLine2) {
this.addrLine2 = addrLine2;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Hibernate Mapping for Student.hbm.xml
Student.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="Student" table="STUDENT">
<id name="id" type="long" column="ID"/>
<property name="name" column="NAME"/>
<component name="address" class="Address">
<property name="houseNumber" column="HOUSE_NUMBER" not-null="true"/>
<property name="addrLine1" column="ADDRLINE1"/>
<property name="addrLine2" column="ADDRLINE2"/>
<property name="phone" column="PHONE"/>
</component>
</component>
</class>
</hibernate-mapping>
Now I want to access the property houseNumber, phone using detached criteria
but when I try to get the property as address.phone
I get the errors as
org.hibernate.QueryException: could not resolve property: phone of: Student
The error occurs because Student really does not have the "phone", which is a Address property.
The correct usage should be something like session.createCriteria( Student.class ).add( Restrictions.eq( "address.phone", "myPhoneNumber" ) ).list() for common criterias.
The version with DetachedCriteria is
DetachedCriteria criteria = DetachedCriteria.forClass( Student.class ).add(Restrictions.eq( "address.phone", "99999999" ) );
List students = criteria.getExecutableCriteria( session ).list();
anyone tell me where I am wrong. Already had wasted a day.
Problem is why hibernate(v 3.5.0 FINAL) is not creating foreign key in cdl_group_module table? It just create table having only single column i.e id(PK). I want one-to-one unidirectional mapping. I can not use bi-directional mapping because cdl_group is also used by other tables same as for cdl_module.
Below is my POJO.
public class CDLGroupModule extends AbstractDomainObject {
/**
*
*/
private static final long serialVersionUID = 1L;
private Group group;
private CDLModule cdlModule;
/**
* #return the group
*/
public Group getGroup() {
return group;
}
/**
* #param group
* the group to set
*/
public void setGroup(Group group) {
this.group = group;
}
/**
* #return the cdlModule
*/
public CDLModule getCdlModule() {
return cdlModule;
}
/**
* #param cdlModule
* the cdlModule to set
*/
public void setCdlModule(CDLModule cdlModule) {
this.cdlModule = cdlModule;
}
}
public class Group extends AbstractDomainObject{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String description;
public Group() {
}
public Group(String name, String description) {
this.name = name;
this.description = description;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the description
*/
public String getDescription() {
return description;
}
/**
* #param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "[Group : { id : " + id + ", name : " + name + ", description :" + description + " }]";
}
}
public class CDLModule extends AbstractDomainObject {
/**
*
*/
private static final long serialVersionUID = 1L;
private CdlModuleEnum module;
/**
* #return the module
*/
public CdlModuleEnum getModule() {
return module;
}
/**
* #param module
* the module to set
*/
public void setModule(CdlModuleEnum module) {
this.module = module;
}
}
Below is my 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 package="com.qait.cdl.commons.domain">
<class name="CDLGroupModule" table="cdl_group_module">
<id name="id" type="long" column="id">
<generator class="native" />
</id>
<!-- <many-to-one name="group" cascade="all" fetch="join"
lazy="false" class="Group" not-null="true" unique="true"/>
<many-to-one name="cdlModule" cascade="all" fetch="join"
lazy="false" class="CDLModule" not-null="true" unique="true"/> -->
<one-to-one name="group" cascade="all-delete-orphan" fetch="join"
lazy="false" class="Group" />
<one-to-one name="cdlModule" cascade="all-delete-orphan" fetch="join"
lazy="false" class="CDLModule" />
</class>
</hibernate-mapping>
Hibernate created cdl_group and cdl_module table already successfully. My id property is present in AbstractDomainObject class which all POJO's are extending. If I tried many-to-one mapping using unique=true instead of one-to-one mapping than hibernate doesn't even create table.
What is the reason behind that?
Any kind of help will be appreciable. You can ask if you want more info from my side.
It seems that hibernate for one to one will try to map on the PK. When fetching cdl_group_module it will try to populate the relationship with any cdl_group with the same PK as the PK of cdl_group_module. This gets pretty bogey when you remove and add new cdl_group enities.
Try setting this property to create a FK:
"property-ref (optional): the name of a property of the associated class that is joined to the primary key of this class. If not specified, the primary key of the associated class is used."