I'm working on a project and this is first time that I'm using hibernate tech.
I made my hibernate configuration file as
<?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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">diobookbla</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mobil</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.default_schema">mobil</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
</session-factory>
</hibernate-configuration>
And this I've done my reverse engineering configuration so I get my MySQL tables as Java classes.
This is my User Class;
package Tables;
// default package
// Generated Nov 24, 2012 1:08:44 AM by Hibernate Tools 3.4.0.CR1
import java.util.HashSet;
import java.util.Set;
/**
* Users generated by hbm2java
*/
public class Users implements java.io.Serializable {
private Integer userId;
private Integer userFbId;
private String userFbToken;
private String userName;
private String userLastName;
private String userEmail;
private String userAdress;
private String userFavouritedTopicsCount;
private String userCreatedTopicsCount;
private String userRecommendedTopicsCount;
private Integer userFollowingsCount;
private Integer userFollowersCount;
private String userBio;
private String userProfilePicUrl;
private Boolean userIsOnline;
private Integer userPoint;
private Set topicses = new HashSet(0);
private Set mentionsForMentionedId = new HashSet(0);
private Set favouritetopicses = new HashSet(0);
private Set mentionsForMentionerId = new HashSet(0);
private Set postlikes = new HashSet(0);
private Set userfollowsForFollowingId = new HashSet(0);
private Set topicrecommends = new HashSet(0);
private Set userfollowsForFollowerId = new HashSet(0);
public Users() {
}
public Users(Integer userFbId, String userFbToken, String userName,
String userLastName, String userEmail, String userAdress,
String userFavouritedTopicsCount, String userCreatedTopicsCount,
String userRecommendedTopicsCount, Integer userFollowingsCount,
Integer userFollowersCount, String userBio,
String userProfilePicUrl, Boolean userIsOnline, Integer userPoint,
Set topicses, Set mentionsForMentionedId, Set favouritetopicses,
Set mentionsForMentionerId, Set postlikes,
Set userfollowsForFollowingId, Set topicrecommends,
Set userfollowsForFollowerId) {
this.userFbId = userFbId;
this.userFbToken = userFbToken;
this.userName = userName;
this.userLastName = userLastName;
this.userEmail = userEmail;
this.userAdress = userAdress;
this.userFavouritedTopicsCount = userFavouritedTopicsCount;
this.userCreatedTopicsCount = userCreatedTopicsCount;
this.userRecommendedTopicsCount = userRecommendedTopicsCount;
this.userFollowingsCount = userFollowingsCount;
this.userFollowersCount = userFollowersCount;
this.userBio = userBio;
this.userProfilePicUrl = userProfilePicUrl;
this.userIsOnline = userIsOnline;
this.userPoint = userPoint;
this.topicses = topicses;
this.mentionsForMentionedId = mentionsForMentionedId;
this.favouritetopicses = favouritetopicses;
this.mentionsForMentionerId = mentionsForMentionerId;
this.postlikes = postlikes;
this.userfollowsForFollowingId = userfollowsForFollowingId;
this.topicrecommends = topicrecommends;
this.userfollowsForFollowerId = userfollowsForFollowerId;
}
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getUserFbId() {
return this.userFbId;
}
public void setUserFbId(Integer userFbId) {
this.userFbId = userFbId;
}
public String getUserFbToken() {
return this.userFbToken;
}
public void setUserFbToken(String userFbToken) {
this.userFbToken = userFbToken;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserLastName() {
return this.userLastName;
}
public void setUserLastName(String userLastName) {
this.userLastName = userLastName;
}
public String getUserEmail() {
return this.userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUserAdress() {
return this.userAdress;
}
public void setUserAdress(String userAdress) {
this.userAdress = userAdress;
}
public String getUserFavouritedTopicsCount() {
return this.userFavouritedTopicsCount;
}
public void setUserFavouritedTopicsCount(String userFavouritedTopicsCount) {
this.userFavouritedTopicsCount = userFavouritedTopicsCount;
}
public String getUserCreatedTopicsCount() {
return this.userCreatedTopicsCount;
}
public void setUserCreatedTopicsCount(String userCreatedTopicsCount) {
this.userCreatedTopicsCount = userCreatedTopicsCount;
}
public String getUserRecommendedTopicsCount() {
return this.userRecommendedTopicsCount;
}
public void setUserRecommendedTopicsCount(String userRecommendedTopicsCount) {
this.userRecommendedTopicsCount = userRecommendedTopicsCount;
}
public Integer getUserFollowingsCount() {
return this.userFollowingsCount;
}
public void setUserFollowingsCount(Integer userFollowingsCount) {
this.userFollowingsCount = userFollowingsCount;
}
public Integer getUserFollowersCount() {
return this.userFollowersCount;
}
public void setUserFollowersCount(Integer userFollowersCount) {
this.userFollowersCount = userFollowersCount;
}
public String getUserBio() {
return this.userBio;
}
public void setUserBio(String userBio) {
this.userBio = userBio;
}
public String getUserProfilePicUrl() {
return this.userProfilePicUrl;
}
public void setUserProfilePicUrl(String userProfilePicUrl) {
this.userProfilePicUrl = userProfilePicUrl;
}
public Boolean getUserIsOnline() {
return this.userIsOnline;
}
public void setUserIsOnline(Boolean userIsOnline) {
this.userIsOnline = userIsOnline;
}
public Integer getUserPoint() {
return this.userPoint;
}
public void setUserPoint(Integer userPoint) {
this.userPoint = userPoint;
}
public Set getTopicses() {
return this.topicses;
}
public void setTopicses(Set topicses) {
this.topicses = topicses;
}
public Set getMentionsForMentionedId() {
return this.mentionsForMentionedId;
}
public void setMentionsForMentionedId(Set mentionsForMentionedId) {
this.mentionsForMentionedId = mentionsForMentionedId;
}
public Set getFavouritetopicses() {
return this.favouritetopicses;
}
public void setFavouritetopicses(Set favouritetopicses) {
this.favouritetopicses = favouritetopicses;
}
public Set getMentionsForMentionerId() {
return this.mentionsForMentionerId;
}
public void setMentionsForMentionerId(Set mentionsForMentionerId) {
this.mentionsForMentionerId = mentionsForMentionerId;
}
public Set getPostlikes() {
return this.postlikes;
}
public void setPostlikes(Set postlikes) {
this.postlikes = postlikes;
}
public Set getUserfollowsForFollowingId() {
return this.userfollowsForFollowingId;
}
public void setUserfollowsForFollowingId(Set userfollowsForFollowingId) {
this.userfollowsForFollowingId = userfollowsForFollowingId;
}
public Set getTopicrecommends() {
return this.topicrecommends;
}
public void setTopicrecommends(Set topicrecommends) {
this.topicrecommends = topicrecommends;
}
public Set getUserfollowsForFollowerId() {
return this.userfollowsForFollowerId;
}
public void setUserfollowsForFollowerId(Set userfollowsForFollowerId) {
this.userfollowsForFollowerId = userfollowsForFollowerId;
}
}
This are my classes that uses the my Users class
public boolean SaveDatabase(Object object) {
try {
SessionFactory sessionfactory = new Configuration().configure()
.buildSessionFactory();
session = sessionfactory.openSession();
try {
session.save(object);
session.flush();
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
} finally {
session.close();
}
return true;
}
and
public boolean RegisterUsers(Users user) {
if (SaveDatabase(user)) {
return true;
} else {
return false;
}
}
At least this is my test class.
import Tables.Users;
import DAO.LogIn;
public class Test {
public static void main(String[] args) {
//Test RegisterUser and GetUsersWithId in here
LogIn test = new LogIn();
Users user = new Users();
user.setUserEmail("email");
user.setUserAdress("adres here");
user.setUserFbId(3);
test.RegisterUsers(user);
}
}
When I execute my test class I got this error;
Unknown entity: Tables.Users .
I've done some researches about this and it I got up with that I must create persistence.xml file or use spring tech.
Sorry for long post, I'm waiting for any helps.
Thanks.
you need to let Hibernate know that which class would be mapped to persistent layer(database table for example). You could either do that with annotation or using hbm.xml approach.
In your User class, I didn't see any hibernate annotation. I therefore guess you wanna do it with hbm.xml.
You need add something like
<mapping resource="path/to/your/User.hbm.xml"/>
to your hibernate.cfg.xml.
And of course you have to create the User.hbm.xml as well. do some research on that, how to do hibernate mappings.
Personally I suggest that you do hibernate mapping with annotations. There are tons of resources about that on net.
Good luck!
Related
When I use a distance API I get this response:
<?xml version="1.0" encoding="utf-8"?>
<Response xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">
<Copyright>Copyright © 2020 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.</Copyright>
<BrandLogoUri>http://dev.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>
<StatusCode>200</StatusCode>
<StatusDescription>OK</StatusDescription>
<AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>
<TraceId>df8ee9b6422846f0b97644c0a631deb8|DU00000D71|0.0.0.0|DU000005EC, DU00000480|Ref A: F00DC0285E97417B99490A8C98E65E31 Ref B: DB3EDGE1608 Ref C: 2020-06-09T18:53:54Z|Ref A: 69E0F633DF6448A89B2B904773DF19AB Ref B: DB3EDGE0807 Ref C: 2020-06-09T18:53:54Z</TraceId>
<ResourceSets>
<ResourceSet>
<EstimatedTotal>1</EstimatedTotal>
<Resources>
<Route>
<Id>v69,h1509963868,i0,a2,cen-US,dAAAAAAAAAAA1,y0,s1,m1,o1,t4,wWriswmZmQkBa9bnail0kQA2~BFnWzEBwiKgBBH_gASHtAT8A0~VHVuaXMsIFR1bmlzaWE1~~~~v11,w-Ki_XmFfQUC94xQdyYUlQA2~BFnWzEBYRLoBBH_gAc1znT4B0~U2ZheCwgVHVuaXNpYQ2~~~~v11,k1</Id>
<BoundingBox>
<SouthLatitude>34.74499</SouthLatitude>
<WestLongitude>10.18235</WestLongitude>
<NorthLatitude>36.800014</NorthLatitude>
<EastLongitude>10.76493</EastLongitude>
</BoundingBox>
<DistanceUnit>Kilometer</DistanceUnit>
<DurationUnit>Second</DurationUnit>
<TravelDistance>271.101</TravelDistance>
...
I want to get the value of TravelDistance.
If possible a full code because I have been trying with this for long time and no solution.
You can use XmlMapper of jackson to de/serialize your XML.
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.8</version>
</dependency>
so you shall need to create an instance of it and deserialize as follows :
XmlMapper mapper = new XmlMapper();
Response value = xmlMapper.readValue("<Response>..</Response>", Response.class);
So you will need to create your object model that reflects your XML.
public class Response {
private String Copyright;
private String BrandLogoUri;
private String StatusCode;
private String StatusDescription;
private String AuthenticationResultCode;
private String TraceId;
ResourceSets ResourceSetsObject;
// Getter Methods
public String getCopyright() {
return Copyright;
}
public String getBrandLogoUri() {
return BrandLogoUri;
}
public String getStatusCode() {
return StatusCode;
}
public String getStatusDescription() {
return StatusDescription;
}
public String getAuthenticationResultCode() {
return AuthenticationResultCode;
}
public String getTraceId() {
return TraceId;
}
public ResourceSets getResourceSets() {
return ResourceSetsObject;
}
// Setter Methods
public void setCopyright(String Copyright) {
this.Copyright = Copyright;
}
public void setBrandLogoUri(String BrandLogoUri) {
this.BrandLogoUri = BrandLogoUri;
}
public void setStatusCode(String StatusCode) {
this.StatusCode = StatusCode;
}
public void setStatusDescription(String StatusDescription) {
this.StatusDescription = StatusDescription;
}
public void setAuthenticationResultCode(String AuthenticationResultCode) {
this.AuthenticationResultCode = AuthenticationResultCode;
}
public void setTraceId(String TraceId) {
this.TraceId = TraceId;
}
public void setResourceSets(ResourceSets ResourceSetsObject) {
this.ResourceSetsObject = ResourceSetsObject;
}
}
public class ResourceSets {
ResourceSet ResourceSetObject;
// Getter Methods
public ResourceSet getResourceSet() {
return ResourceSetObject;
}
// Setter Methods
public void setResourceSet(ResourceSet ResourceSetObject) {
this.ResourceSetObject = ResourceSetObject;
}
}
public class ResourceSet {
private String EstimatedTotal;
Resources ResourcesObject;
// Getter Methods
public String getEstimatedTotal() {
return EstimatedTotal;
}
public Resources getResources() {
return ResourcesObject;
}
// Setter Methods
public void setEstimatedTotal(String EstimatedTotal) {
this.EstimatedTotal = EstimatedTotal;
}
public void setResources(Resources ResourcesObject) {
this.ResourcesObject = ResourcesObject;
}
}
public class Resources {
Route RouteObject;
// Getter Methods
public Route getRoute() {
return RouteObject;
}
// Setter Methods
public void setRoute(Route RouteObject) {
this.RouteObject = RouteObject;
}
}
public class Route {
private String Id;
BoundingBox BoundingBoxObject;
private String DistanceUnit;
private String DurationUnit;
private String TravelDistance;
// Getter Methods
public String getId() {
return Id;
}
public BoundingBox getBoundingBox() {
return BoundingBoxObject;
}
public String getDistanceUnit() {
return DistanceUnit;
}
public String getDurationUnit() {
return DurationUnit;
}
public String getTravelDistance() {
return TravelDistance;
}
// Setter Methods
public void setId(String Id) {
this.Id = Id;
}
public void setBoundingBox(BoundingBox BoundingBoxObject) {
this.BoundingBoxObject = BoundingBoxObject;
}
public void setDistanceUnit(String DistanceUnit) {
this.DistanceUnit = DistanceUnit;
}
public void setDurationUnit(String DurationUnit) {
this.DurationUnit = DurationUnit;
}
public void setTravelDistance(String TravelDistance) {
this.TravelDistance = TravelDistance;
}
}
public class BoundingBox {
private String SouthLatitude;
private String WestLongitude;
private String NorthLatitude;
private String EastLongitude;
// Getter Methods
public String getSouthLatitude() {
return SouthLatitude;
}
public String getWestLongitude() {
return WestLongitude;
}
public String getNorthLatitude() {
return NorthLatitude;
}
public String getEastLongitude() {
return EastLongitude;
}
// Setter Methods
public void setSouthLatitude(String SouthLatitude) {
this.SouthLatitude = SouthLatitude;
}
public void setWestLongitude(String WestLongitude) {
this.WestLongitude = WestLongitude;
}
public void setNorthLatitude(String NorthLatitude) {
this.NorthLatitude = NorthLatitude;
}
public void setEastLongitude(String EastLongitude) {
this.EastLongitude = EastLongitude;
}
}
Hi guys i'me having troubles using morphia for mongodb this is what im creating.
Im creating a spigot plugin for my hub server and im using mongodb with morphia for store my user object to my collection and this object only store 1 user instead of saving all users into the collection.
My user object
#Entity(value = "clientdata", noClassnameStored = true)
public class ClientData {
#Id
public int id;
#Indexed(options = #IndexOptions(unique = true))
private String uuid;
#Indexed
private String lastName, username, lastLoginDate, ip;
#Indexed
private int level, exp, joins, coins, pearls;
#Property("hats")
private List<Integer> hatsOwned;
public ClientData(){
this.hatsOwned = new ArrayList<>();
if(this.hatsOwned.isEmpty()){
this.hatsOwned.add(0);
}
}
public int getId() {
return id;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public void setId(int id) {
this.id = id;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
public int getJoins() {
return joins;
}
public void setJoins(int joins) {
this.joins = joins;
}
public void addJoins(int joins) {
this.joins += joins;
}
public int getCoins() {
return coins;
}
public void setCoins(int coins) {
this.coins = coins;
}
public int getPearls() {
return pearls;
}
public void setPearls(int pearls) {
this.pearls = pearls;
}
public List<Integer> getHatsOwned() {
return hatsOwned;
}
public void setHatsOwned(List<Integer> hatsOwned) {
this.hatsOwned = hatsOwned;
}
public void addNewHatOwned(int hatID){
this.hatsOwned.add(hatID);
}
public String getLastLoginDate() {
return lastLoginDate;
}
public void setLastLoginDate(String lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
}
My mongo manager class
public class MongoManager {
private static MongoManager ins = new MongoManager();
private MongoClient mc;
private Morphia morphia;
private Datastore datastore;
private ClientDAO userDAO;
public static MongoManager get() {
return ins;
}
public void init() {
ServerAddress addr = new ServerAddress("127.0.0.1", 27017);
List<MongoCredential> credentials = new ArrayList<>();
credentials.add(MongoCredential.createCredential("union", "admin", "union16".toCharArray()));
mc = new MongoClient(addr, credentials);
morphia = new Morphia();
morphia.map(ClientData.class);
datastore = morphia.createDatastore(mc, "admin");
datastore.ensureIndexes();
userDAO = new ClientDAO(ClientData.class, datastore);
}
public void disconnect(){
this.mc.close();
}
public ClientData getUserByPlayer(Player player) {
ClientData du = userDAO.findOne("uuid", player.getUniqueId().toString());
long time = System.currentTimeMillis();
if (du == null) {
du = new ClientData();
du.setUuid(player.getUniqueId().toString());
du.setCoins(0);
du.setExp(0);
du.setJoins(0);
du.setLastLoginDate(DateFormat.getTimeInstance().format(time));
du.setLevel(0);
du.setPearls(0);
du.setIp(player.getAddress().getAddress().toString());
du.setUsername(player.getDisplayName());
du.setLastName(player.getName());
du.setHatsOwned(null);
userDAO.save(du);
}
return du;
}
public void saveUser(ClientData user) {
userDAO.save(user);
}
public List<ClientData> getAllUsers() {
return userDAO.find().asList();
}
}
You can't insert more than one because you have duplicateKey: you can't use an #id with primitive type without setting a unique value yourself.
You defined your id like this:
#Id
public int id;
Even though you never set any value for id, primitive types are initialized to 0, so you end up trying to insert multiple documents with the same key.
Solution:
You can either :
change your id to String: #Id String id;
change your id to ObjectId: #Id ObjectId id;
keep #Id int id and manually set a unique value to it (player.getUniqueId() for instance).
The first 2 options will work because they won't be initialized and will be null. Mongo will then generate a unique id for you.
Hi This is my Row Mapper class.
public class UserRowMapper implements RowMapper<UserData> {
#Override
public UserData mapRow(ResultSet resultSet, int line) throws SQLException {
UserData userData = new UserData();
try
{
userData.setUserID(resultSet.getString("User_ID"));
userData.setUserName(resultSet.getString("User_Name"));
userData.setUserPassword(resultSet.getString("User_Password"));
userData.setUserRole(resultSet.getString("User_Role"));
userData.setUserStatus(resultSet.getString("User_Status"));
userData.setUserLogStatus(resultSet.getString("UserLog_Status"));
userData.setUserAccountName(resultSet.getString("User_AccountName"));
userData.setUserAccountID(resultSet.getString("User_AccountID"));
userData.setUserEmailID(resultSet.getString("User_EmailID"));
userData.setUserPasswordStatus(resultSet.getString("User_Password_ExpiryStatus"));
userData.setUserIDStatus(resultSet.getString("User_ID_Status"));
userData.setAcatTenantID(resultSet.getLong("acatTenant_ID"));
userData.setUserRoleCode(resultSet.getLong("User_Role_Code"));
userData.setUserSkillSetCode(resultSet.getLong("User_SkillSet_Code"));
userData.setUserAccountCode(resultSet.getLong("User_Account_Code"));
return userData;
}
catch (EmptyResultDataAccessException e)
{
return null;
}
}
}
and this is my Model class.
public class UserData {
private String userID;
private String userPassword;
private String userRole;
private String userStatus;
private String userLogStatus;
private String userName;
private String userAccountName;
private String userAccountID;
private String userIDStatus;
private String userPasswordStatus;
private String userEmailID;
private String userAdminID;
private String deactivationComment;
private String reqPageID;
private String userSessionID;
private String reqFunctionalityID;
private long userAccountCode;
private long userRoleCode;
private long userSkillSetCode;
private long acatTenantID;
public long getUserAccountCode() {
return userAccountCode;
}
public void setUserAccountCode(long userAccountCode) {
this.userAccountCode = userAccountCode;
}
public long getUserRoleCode() {
return userRoleCode;
}
public void setUserRoleCode(long userRoleCode) {
this.userRoleCode = userRoleCode;
}
public long getUserSkillSetCode() {
return userSkillSetCode;
}
public void setUserSkillSetCode(long userSkillSetCode) {
this.userSkillSetCode = userSkillSetCode;
}
public long getAcatTenantID() {
return acatTenantID;
}
public void setAcatTenantID(long acatTenantID) {
this.acatTenantID = acatTenantID;
}
public String getReqFunctionalityID() {
return reqFunctionalityID;
}
public void setReqFunctionalityID(String reqFunctionalityID) {
this.reqFunctionalityID = reqFunctionalityID;
}
public String getReqPageID() {
return reqPageID;
}
public void setReqPageID(String reqPageID) {
this.reqPageID = reqPageID;
}
public String getUserSessionID() {
return userSessionID;
}
public void setUserSessionID(String userSessionID) {
this.userSessionID = userSessionID;
}
public String getUserAdminID() {
return userAdminID;
}
public void setUserAdminID(String userAdminID) {
this.userAdminID = userAdminID;
}
public String getDeactivationComment() {
return deactivationComment;
}
public void setDeactivationComment(String deactivationComment) {
this.deactivationComment = deactivationComment;
}
public String getUserIDStatus() {
return userIDStatus;
}
public void setUserIDStatus(String userIDStatus) {
this.userIDStatus = userIDStatus;
}
public String getUserPasswordStatus() {
return userPasswordStatus;
}
public void setUserPasswordStatus(String userPasswordStatus) {
this.userPasswordStatus = userPasswordStatus;
}
public String getUserEmailID() {
return userEmailID;
}
public void setUserEmailID(String userEmailID) {
this.userEmailID = userEmailID;
}
public String getUserAccountID() {
return userAccountID;
}
public void setUserAccountID(String userAccountID) {
this.userAccountID = userAccountID;
}
public String getUserAccountName() {
return userAccountName;
}
public void setUserAccountName(String userAccountName) {
this.userAccountName = userAccountName;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
public String getUserStatus() {
return userStatus;
}
public void setUserStatus(String userStatus) {
this.userStatus = userStatus;
}
public String getUserLogStatus() {
return userLogStatus;
}
public void setUserLogStatus(String userLogStatus) {
this.userLogStatus = userLogStatus;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
The above classes are my Row Mapper and Model class.i do not know how to write junit test class for Row Mapper class .please any one guide me how to write junit test for these classes.
Hi here is my Junit test code for above classes.
public class UserRowMapperTest {
UserRowMapper userRowMapper=null;
#Before
public void runBeforeEachTest(){
userRowMapper= new UserRowMapper();
}
#After
public void runAfterEachTest(){
userRowMapper=null;
}
#Test
public void testMapRow(){
userRowMapper.mapRow(resultSet, line);
}
}
From my point of view there is nothing to test here.
You should create unit tests only for the methods which have some business logic. I don't see the reason to test the methods which are using just getters and setters because in general they don't do anything.
However, if you want just to practice this is the advice what you could do for the unit test. First of all check some questions on how to write the unit tests because it feels like you don't understand what you need/want to achieve.
In general this is the sketch of what you want:
#Test
public void testMapRow(){
// SETUP SUT
UserRowMapper userRowMapper = new UserRowMapper()
// fill (prepare) in the Object that you want to pass to a method.
ResultSet resultSet = createResultSet();
// EXERCISE
UserData resultData = userRowMapper.mapRow(resultSet, line);
// VERIFY
Assert.assertEquals(expectedValue, resultData.getSomeValue())
}
p.s. By the way, there is no point in line parameter in this method because you don't use it.
And about the NullPointerException, please, have a look to quite popular question about it.
How to pass array of string in insert query statement in ibatis. On passing string array as parameter it is giving me this exception of ibatis -
Can't infer the SQL type to use for an instance of [Ljava.lang.String;. Use setObject() with an explicit Types value to specify the type to use.
How to solve this error ?
My method is -
public void insertCampaignData(String campaignData, ObjectMapper jsonObjMapper) {
Campaign campaign = null;
SqlSession session = null;
IfrmCreateCampaign createCampaign = null;
try {
campaign = jsonObjMapper.readValue(campaignData,Campaign.class);
session = DBConnectionFactory.getNewSession();
createCampaign = session.getMapper(IfrmCreateCampaign.class);
createCampaign.insertCampaignData(campaign);
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
My entity class is -
import java.io.File;
import java.util.Date;
public class Campaign {
private long campaignId;
private String campaignName;
private long keywordId;
private String brandName;
private String clientName;
private String mobileNum;
private Date startTime;
private Date endTime;
private double campaignBudget;
private double allocatedFund;
private double campaignRate;
private boolean basicTgt;
private boolean customTgt;
private boolean advTgt;
private boolean chechme;
private boolean couponSend;
private String couponFrom;
private String couponTo;
private String couponFilePath;
private File[] couponFile;
private String[] couponFileFileName;
private String[] couponFileContent;
private String callbackUrl;
private String status;
private int campaignTypeId;
private long roAmount;
// edit
private int roType;
public int getRoType() {
return roType;
}
public void setRoType(int roType) {
this.roType = roType;
}
// edit
private String strStartTime;
private String strEndTime;
private String keyword;
private String keywordNum;
private int goal;
private double spentAmount;
private int goalAchievePercent;
private int dial;
private int uniqueDial;
private long userId;
private double campaignTotalAmount;
private double operatorShare;
private long responseCount;
private String strRoPdfFileName;
private File[] roPdf;
private String[] roPdfFileName;
private String[] roPdfContent;
public long getCampaignId() {
return campaignId;
}
public void setCampaignId(long campaignId) {
this.campaignId = campaignId;
}
public String getCampaignName() {
return campaignName;
}
public void setCampaignName(String campaignName) {
this.campaignName = campaignName;
}
public long getKeywordId() {
return keywordId;
}
public void setKeywordId(long keywordId) {
this.keywordId = keywordId;
}
public String getKeywordNum() {
return keywordNum;
}
public void setKeywordNum(String keywordNum) {
this.keywordNum = keywordNum;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getMobileNum() {
return mobileNum;
}
public void setMobileNum(String mobileNum) {
this.mobileNum = mobileNum;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public double getCampaignBudget() {
return campaignBudget;
}
public void setCampaignBudget(double campaignBudget) {
this.campaignBudget = campaignBudget;
}
public double getAllocatedFund() {
return allocatedFund;
}
public void setAllocatedFund(double allocatedFund) {
this.allocatedFund = allocatedFund;
}
public double getCampaignRate() {
return campaignRate;
}
public void setCampaignRate(double campaignRate) {
this.campaignRate = campaignRate;
}
public boolean isBasicTgt() {
return basicTgt;
}
public void setBasicTgt(boolean basicTgt) {
this.basicTgt = basicTgt;
}
public boolean isCustomTgt() {
return customTgt;
}
public void setCustomTgt(boolean customTgt) {
this.customTgt = customTgt;
}
public boolean isAdvTgt() {
return advTgt;
}
public void setAdvTgt(boolean advTgt) {
this.advTgt = advTgt;
}
public boolean isChechme() {
return chechme;
}
public void setChechme(boolean chechme) {
this.chechme = chechme;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getStrStartTime() {
return strStartTime;
}
public void setStrStartTime(String strStartTime) {
this.strStartTime = strStartTime;
}
public String getStrEndTime() {
return strEndTime;
}
public void setStrEndTime(String strEndTime) {
this.strEndTime = strEndTime;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public int getGoal() {
return goal;
}
public void setGoal(int goal) {
this.goal = goal;
}
public double getSpentAmount() {
return spentAmount;
}
public void setSpentAmount(double spentAmount) {
this.spentAmount = spentAmount;
}
public int getGoalAchievePercent() {
return goalAchievePercent;
}
public void setGoalAchievePercent(int goalAchievePercent) {
this.goalAchievePercent = goalAchievePercent;
}
public int getDial() {
return dial;
}
public void setDial(int dial) {
this.dial = dial;
}
public int getUniqueDial() {
return uniqueDial;
}
public void setUniqueDial(int uniqueDial) {
this.uniqueDial = uniqueDial;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public boolean isCouponSend() {
return couponSend;
}
public void setCouponSend(boolean couponSend) {
this.couponSend = couponSend;
}
public String getCouponFrom() {
return couponFrom;
}
public void setCouponFrom(String couponFrom) {
this.couponFrom = couponFrom;
}
public String getCouponTo() {
return couponTo;
}
public void setCouponTo(String couponTo) {
this.couponTo = couponTo;
}
public String getCouponFilePath() {
return couponFilePath;
}
public void setCouponFilePath(String couponFilePath) {
this.couponFilePath = couponFilePath;
}
public File[] getCouponFile() {
return couponFile;
}
public void setCouponFile(File[] couponFile) {
this.couponFile = couponFile;
}
public String[] getCouponFileFileName() {
return couponFileFileName;
}
public void setCouponFileFileName(String[] couponFileFileName) {
this.couponFileFileName = couponFileFileName;
}
public String[] getCouponFileContent() {
return couponFileContent;
}
public void setCouponFileContent(String[] couponFileContent) {
this.couponFileContent = couponFileContent;
}
public String getCallbackUrl() {
return callbackUrl;
}
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
public int getCampaignTypeId() {
return campaignTypeId;
}
public void setCampaignTypeId(int campaignTypeId) {
this.campaignTypeId = campaignTypeId;
}
public long getRoAmount() {
return roAmount;
}
public void setRoAmount(long roAmount) {
this.roAmount = roAmount;
}
public double getOperatorShare() {
return operatorShare;
}
public void setOperatorShare(double operatorShare) {
this.operatorShare = operatorShare;
}
public long getResponseCount() {
return responseCount;
}
public void setResponseCount(long responseCount) {
this.responseCount = responseCount;
}
public double getCampaignTotalAmount() {
return campaignTotalAmount;
}
public void setCampaignTotalAmount(double campaignTotalAmount) {
this.campaignTotalAmount = campaignTotalAmount;
}
public String getStrRoPdfFileName() {
return strRoPdfFileName;
}
public void setStrRoPdfFileName(String strRoPdfFileName) {
this.strRoPdfFileName = strRoPdfFileName;
}
public File[] getRoPdf() {
return roPdf;
}
public void setRoPdf(File[] roPdf) {
this.roPdf = roPdf;
}
public String[] getRoPdfFileName() {
return roPdfFileName;
}
public void setRoPdfFileName(String[] roPdfFileName) {
this.roPdfFileName = roPdfFileName;
}
public String[] getRoPdfContent() {
return roPdfContent;
}
public void setRoPdfContent(String[] roPdfContent) {
this.roPdfContent = roPdfContent;
}
}
My xml mapping file is -
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mogae.starStarWebServices.db.dao.IfrmCreateCampaign">
<insert id="insertCampaignData" statementType="PREPARED" >
insert into campaign(campaign_id,campaign_name,keyword_id,brand_name,client_name,mobile_num,start_time,end_time,campaign_type_id,ro_amount,ro_type,ro_pdf_file_name,campaign_budget,allocated_fund,campaign_rate,is_basic_tgt,is_custom_tgt,is_adv_tgt,is_checkme,is_coupon_send,coupon_from,coupon_to,coupon_file,callback_url,status) values (#{campaignId},#{campaignName},#{keywordId},#{brandName},#{clientName},#{mobileNum},#{startTime},#{endTime},#{campaignTypeId},#{roAmount},#{roType},
#{strRoPdfFileName},#{campaignBudget},#{allocatedFund},#{campaignRate},#{basicTgt},#{customTgt},#{advTgt},#{chechme},#{couponSend},#{couponFrom},#{couponTo},#{couponFileFileName},#{callbackUrl},#{status});
</insert>
<insert id="insertKeywordData" statementType="PREPARED" >
insert into keywords(keyword_id,keyword,keyword_num,booked_by,purchased_on,expires_on,status) values (#{keywordId},#{keyword},#{keywordNum},#{bookedBy},#{purchasedOn},#{expiresOn},#{status})
</insert>
</mapper>
imagine I have a table called Photo and a table called Tag.
A Photo can have any amount of tags. Like a picture of the Brandenburg Gate in Berlin has as tags "Berlin", "Gate", ...
Now there is a second photo with the Berlin Reichstag and has also "Berlin" as one of its tags.
At the moment this would now get saved redundantly in my database, this means in my Tag table "Berlin" appears twice and in my join table that has been created by hibernate each tupel directs to its own "Berlin"-Tag.
I don't like this situation, because this means I'm saving redundant data in my database. I would much more like the case that the tag "Berlin" gets only saved once in my Tag-table and each Photo that has this tag gets the reference on this one tag object.
So summarized:
Before (I hope this now gets displayed correctly, when I send this question)
PHOTO
ID | PhotoName
1 | Brandenburg Gate
2 | Reichstag Germany
...| ...
TAG
ID | Tagname
1 | Berlin
2 | Hamster
3 | Berlin
4 | Berlin
5 | Bird
...| ...
PHOTO_TAG (join table)
photoID | tagID
1 | 1
2 | 3
3 | 4
... | ...
Hopefully afterwards:
PHOTO
ID | PhotoName
1 | Brandenburg Gate
2 | Reichstag Germany
...| ...
TAG
ID | Tagname
1 | Berlin
2 | Hamster
3 | Bird
...| ...
PHOTO_TAG (join table)
photoID | tagID
1 | 1
2 | 1
3 | 1
... | ...
As you can see Berlin only needs to get saved once in the Tag table, while there is still no information loss, since the join table references correct on the tupel.
I tried to achieve this with hibernate (I'm not a pro) on a postgresql database. My Photo-Class has an attribute photoTags, which I gave a ManyToMany relationship (I thought that this could mean that every photo can have any amount of tags while every tag can have any amount of photos they're referenced to)
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Tag> photoTags;
But simply, this didn't work. There is a lot of redundant data in my tag table.
a
Now my question: Do you know any sufficient way for me to realize this? Thank for you for every answer and comment (If you need any further information, like my hibernate.cfg.xml, just tell me).
(This Question here is dealing with a similar problem, but the answer is not satisfying for me:
Normalize repeating values in Hibernate - Java)
EDIT: I attach now my hibernate classes:
User.java
import java.util.Date;
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 javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue
private Long id;
#Column(unique = true)
private String userID;
private String userName;
private String userRealName;
private int userPhotoCount;
private Date userPhotoF;
private Date userPhot_1;
private String userLocation;
private String userThumbnailURL;
private int userIsPro;
private int userIsAdmin;
private int userContact;
private int userPhotoS;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Photo> photos;
public User(String userID, String userName, String userRealName, int userPhotoCount,
Date userPhotoF, Date userPhot_1, String userLocation,
String userThumbnailURL, int userIsPro, int userIsAdmin,
int userContact, int userPhotoS, Set<Photo> photos) {
this.userID = userID;
this.userName = userName;
this.userRealName = userRealName;
this.userPhotoCount = userPhotoCount;
this.userPhotoF = userPhotoF;
this.userPhot_1 = userPhot_1;
this.userLocation = userLocation;
this.userThumbnailURL = userThumbnailURL;
this.userIsPro = userIsPro;
this.userIsAdmin = userIsAdmin;
this.userContact = userContact;
this.userPhotoS = userPhotoS;
this.photos = photos;
}
// Hibernate requirement
public User() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getUserRealName() {
return userRealName;
}
public void setUserRealName(String userRealName) {
this.userRealName = userRealName;
}
public int getUserPhotoCount() {
return userPhotoCount;
}
public void setUserPhotoCount(int userPhotoCount) {
this.userPhotoCount = userPhotoCount;
}
public Date getUserPhotoF() {
return userPhotoF;
}
public void setUserPhotoF(Date userPhotoF) {
this.userPhotoF = userPhotoF;
}
public Date getUserPhot_1() {
return userPhot_1;
}
public void setUserPhot_1(Date userPhot_1) {
this.userPhot_1 = userPhot_1;
}
public String getUserLocation() {
return userLocation;
}
public void setUserLocation(String userLocation) {
this.userLocation = userLocation;
}
public String getUserThumbnailURL() {
return userThumbnailURL;
}
public void setUserThumbnailURL(String userThumbnailURL) {
this.userThumbnailURL = userThumbnailURL;
}
public int getUserIsPro() {
return userIsPro;
}
public void setUserIsPro(int userIsPro) {
this.userIsPro = userIsPro;
}
public int getUserIsAdmin() {
return userIsAdmin;
}
public void setUserIsAdmin(int userIsAdmin) {
this.userIsAdmin = userIsAdmin;
}
public int getUserContact() {
return userContact;
}
public void setUserContact(int userContact) {
this.userContact = userContact;
}
public int getUserPhotoS() {
return userPhotoS;
}
public void setUserPhotoS(int userPhotoS) {
this.userPhotoS = userPhotoS;
}
public Set<Photo> getUserPhotos() {
return photos;
}
public void setUserPhotos(Set<Photo> userPhotos) {
this.photos = userPhotos;
}
public void addPhoto(Photo photo){
this.photos.add(photo);
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
Photo.java
import java.util.Date;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
#Entity
public class Photo {
#Id
#GeneratedValue
private Long id;
private Long photoID;
private String photoTitle;
private String photoUrl;
private int photoAccur;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Tag> photoTags;
private int photoTagsCount;
// ist das korrekt?
private int photoCommentCount;
// date objekte
private Date photoDateP;
private Date photoDateT;
private String photoDescription;
// korrekter Name?
private String photoNotes;
private int photoNot_1;
private String photoMedia;
private String photoMed_1;
private int photoLicense;
private int photoIsFam;
private int photoIsFri;
private int photoIsPri;
// x-Achse
private float photoLongitude;
// y-Achse
private float photoLatitude;
public Photo(Long photoID, String photoTitle, String photoURL,
int photoAccur, Set<Tag> photoTags, int photoTagsCount,
int photoCommentCount, Date photoDateP, Date photoDateT,
String photoDescription, String photoNotesCount, int photoNot_1,
String photoMedia, String photoMed_1, int photoLicense,
int photoIsFam, int photoIsFri, int photoIsPri, float photoLongi,
float photoLatit) {
this.photoID = photoID;
this.photoTitle = photoTitle;
this.photoUrl = photoURL;
this.photoAccur = photoAccur;
this.photoTags = photoTags;
this.photoTagsCount = photoTagsCount;
this.photoCommentCount = photoCommentCount;
this.photoDateP = photoDateP;
this.photoDateT = photoDateT;
this.photoDescription = photoDescription;
this.photoNotes = photoNotesCount;
this.photoNot_1 = photoNot_1;
this.photoMedia = photoMedia;
this.photoMed_1 = photoMed_1;
this.photoLicense = photoLicense;
this.photoIsFam = photoIsFam;
this.photoIsFri = photoIsFri;
this.photoIsPri = photoIsPri;
this.photoLongitude = photoLongi;
this.photoLatitude = photoLatit;
}
// hibernate
public Photo() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getPhotoID() {
return photoID;
}
public void setPhotoID(Long photoID) {
this.photoID = photoID;
}
public String getPhotoTitle() {
return photoTitle;
}
public void setPhotoTitle(String photoTitle) {
this.photoTitle = photoTitle;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
public int getPhotoAccur() {
return photoAccur;
}
public void setPhotoAccur(int photoAccur) {
this.photoAccur = photoAccur;
}
public Set<Tag> getPhotoTags() {
return photoTags;
}
public void setPhotoTags(Set<Tag> photoTags) {
this.photoTags = photoTags;
}
public int getPhotoTagsCount() {
return photoTagsCount;
}
public void setPhotoTagsCount(int photoTagsCount) {
this.photoTagsCount = photoTagsCount;
}
public int getPhotoCommentCount() {
return photoCommentCount;
}
public void setPhotoCommentCount(int photoCommentCount) {
this.photoCommentCount = photoCommentCount;
}
public Date getPhotoDateP() {
return photoDateP;
}
public void setPhotoDateP(Date photoDateP) {
this.photoDateP = photoDateP;
}
public Date getPhotoDateT() {
return photoDateT;
}
public void setPhotoDateT(Date photoDateT) {
this.photoDateT = photoDateT;
}
public String getPhotoDescription() {
return photoDescription;
}
public void setPhotoDescription(String photoDescription) {
this.photoDescription = photoDescription;
}
public String getPhotoNotesCount() {
return photoNotes;
}
public void setPhotoNotesCount(String photoNotesCount) {
this.photoNotes = photoNotesCount;
}
public int getPhotoNot_1() {
return photoNot_1;
}
public void setPhotoNot_1(int photoNot_1) {
this.photoNot_1 = photoNot_1;
}
public String getPhotoMedia() {
return photoMedia;
}
public void setPhotoMedia(String photoMedia) {
this.photoMedia = photoMedia;
}
public String getPhotoMed_1() {
return photoMed_1;
}
public void setPhotoMed_1(String photoMed_1) {
this.photoMed_1 = photoMed_1;
}
public int getPhotoLicense() {
return photoLicense;
}
public void setPhotoLicense(int photoLicense) {
this.photoLicense = photoLicense;
}
public int getPhotoIsFam() {
return photoIsFam;
}
public void setPhotoIsFam(int photoIsFam) {
this.photoIsFam = photoIsFam;
}
public int getPhotoIsFri() {
return photoIsFri;
}
public void setPhotoIsFri(int photoIsFri) {
this.photoIsFri = photoIsFri;
}
public int getPhotoIsPri() {
return photoIsPri;
}
public void setPhotoIsPri(int photoIsPri) {
this.photoIsPri = photoIsPri;
}
public float getPhotoLongi() {
return photoLongitude;
}
public void setPhotoLongi(float photoLongi) {
this.photoLongitude = photoLongi;
}
public float getPhotoLatit() {
return photoLatitude;
}
public void setPhotoLatit(float photoLatit) {
this.photoLatitude = photoLatit;
}
}
Tag.java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Tag {
#Id
#GeneratedValue
private Long id;
private String tag;
public Tag(String tag) {
this.tag = tag;
}
public Tag() {
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
My Hibernate.cfg.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>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/GIS</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">mysql15</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.show_sql">false</property>
<mapping class="database.User" />
<mapping class="database.Photo" />
<mapping class="database.Tag" />
</session-factory>
</hibernate-configuration>
**And now some classes that are dealing my session management with hibernate. They're probably not that important, but just in case. **
DAO.java
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.stat.Statistics;
/**
* DAO provides general access methods on the database related to session
* management (opening and closing)
*
*
*
*/
public abstract class DAO {
/**
* Logs about correct behaviour of the hibernate session management
*/
public static Statistics stats = statistics();
/**
* Ensures that every client gets his correct session
*/
private static final ThreadLocal<Session> sessions = new ThreadLocal<>();
/**
* Returns the current hibernate session. Also takes care that there's
* always an open hibernate transaction when needed.
*
* #return Current hibernate session
*/
public static Session getSession() {
Session result = sessions.get();
if (result == null) {
result = HibernateUtil.getSessionFactory().openSession();
sessions.set(result);
result.beginTransaction();
}
return result;
}
/**
* Closes the current hibernate session, if there is one.
*/
public static void closeSession() {
Session sess = sessions.get();
if (sess == null || !sess.isOpen())
return;
sessions.remove();
try {
Throwable error = null;
try {
if (sess.getTransaction().isActive() == true) {
sess.getTransaction().commit();
}
} catch (Throwable e) {
sess.getTransaction().rollback();
error = e;
} finally {
try {
System.out.println("Sessions geöffnet bisher: "
+ stats.getSessionOpenCount());
sess.close();
System.out.println("Sessions geschlossen bisher: "
+ stats.getSessionCloseCount());
} catch (Throwable th) {
if (error != null) {
error.addSuppressed(th);
} else {
throw th;
}
}
}
} catch (HibernateException ex) {
ex.printStackTrace();
}
}
public static Statistics statistics() {
Statistics stats = HibernateUtil.getSessionFactory().getStatistics();
stats.setStatisticsEnabled(true);
return stats;
}
}
UserDAO.java
import java.util.List;
import org.hibernate.Session;
public class UserDAO extends DAO {
public void createUser(User user) {
if (user == null) {
throw new IllegalArgumentException("user must be not null");
}
Session session = getSession();
// speichern des test in der datenbank
session.save(user);
closeSession();
}
public void updateUser(User user) {
if (user == null) {
throw new IllegalArgumentException("User doesnt exist");
}
Session session = getSession();
// updaten des Users in der datenbank
session.saveOrUpdate(user);
closeSession();
}
public User getUser(Long userID) {
Session session = getSession();
#SuppressWarnings("unchecked")
List<User> oneUser = session.createQuery(
"FROM User WHERE id = " + userID).list();
closeSession();
return oneUser.get(0);
}
public User getUserByUserID(String userID) {
Session session = getSession();
#SuppressWarnings("unchecked")
List<User> oneUser = session.createQuery(
"FROM User WHERE userID = '" + userID + "'").list();
closeSession();
if (oneUser.size() > 0) {
return oneUser.get(0);
} else {
// user existiert nicht
return null;
}
}
public List<User> getAllUsers() {
Session session = getSession();
#SuppressWarnings("unchecked")
List<User> allUsers = session.createQuery("FROM users").list();
closeSession();
return allUsers;
}
}
HibernateUtil.java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* HibernateUtil manages the access to the sessionFactory, which ensures that
* there's always an open database session
*
*
*
*/
#SuppressWarnings("deprecation")
public class HibernateUtil {
final private static SessionFactory sessionFactory;
static {
try {
// create the sessionfactory from standardconfig file
sessionFactory = new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory();
} catch (Throwable ex) {
// log the exception
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
/**
* Returns the current SessionFactory
*
* #return Current SessionFactory
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
HibernateListener.java
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* The HibernateListener takes care that hibernate for the database connection
* management gets initialised on the server start.
*/
public class HibernateListener implements ServletContextListener {
/**
* Calls the static initializer of the HibernateUtil class
*/
public void contextInitialized(ServletContextEvent event) {
HibernateUtil.getSessionFactory(); // Just call the static initializer
// of that class
}
/**
* Frees all ressources when the server is being restarted
*/
public void contextDestroyed(ServletContextEvent event) {
HibernateUtil.getSessionFactory().close(); // Free all resources
}
}
The way you are expecting it to work is how it's supposed to work.
I don't see anything wrong in the Hibernate model classes you have posted, so I can only assume that you are setting new Tag instances to the photo instead of loading them and setting them.
When you do that hibernate doesn't know if these objects are equal or not because they don't have an ID set (you just create them remember?).
Load the Tag objects and assign them to photos or if you are hell bent on adding new instances remove cascade all option and override the equals method to consider other details than the ID if the id is not set (null).