what's wrong guys I have that relations in hibernate #oneToMany:
This is in loan class:
#ManyToOne(cascade=CascadeType.ALL)
private users user;
This is in user class:
#OneToMany(mappedBy="user",fetch=FetchType.LAZY)
private Set<loans> loans=new HashSet<loans>(0);
here I have method to insert new loan:
public static void addLoanToUser(Integer userID,String brand,String model,String registration,String loanStart , String loanEnd){
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
users user = (users) session.load(users.class, userID);
Set<loans> loanSet = new HashSet();
loans loan = new loans();
loan.setBrand(brand);
loan.setModel(model);
loan.setRegistration(registration);
loan.setLoanStart(loanStart);
loan.setLoanEnd(loanEnd);
loan.setPaydone("no");
loanSet.add(loan);
user.setLoans(loanSet);
session.saveOrUpdate(user);
session.save(loan);
session.getTransaction().commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
When I insert data to the database there is always NULL on Foreign Key.
I tried to find sth on the stack but nothing helped.
Its because you have to set relation on "key holder" in your case that is loan entity. So
users user = (users) session.load(users.class, userID);
loans loan = new loans();
..... setup
loan.setUser(user)
session.saveOrUpdate(user);
And you do realize, that if user will take new loan, you effectively removes other loans of that user (in current session) by setting brand new user.loans set ? :) I wish banking systems work like that :)
Related
I want to know if it's possible to create custom query for liferay default table like user, userGroup...
I looked at the example but they give examples that on the custom tables (guestbook table)
try this code
public List<User> getUserByRecentChat(long userId){
Session session=null;
SessionFactory sessionFactory = (SessionFactory) PortalBeanLocatorUtil.locate("liferaySessionFactory");
try {
session = sessionFactory.openSession();
String sql = CustomSQLUtil.get(getClass(), "getUserByRecentChat");
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setCacheable(false);
sqlQuery.addEntity("users_", UserImpl.class); // for user table
QueryPos pos = QueryPos.getInstance(sqlQuery);
pos.add(userId);
pos.add(userId);
return (List<User>) sqlQuery.list();
} catch (Exception e) {
e.printStackTrace();
} finally {
sessionFactory.closeSession(session);
}
return null;
}
Yes you can use Custom Query for Liferay Default Tables
Thanks
code:
public void test() {
Session session = sessionFactory.openSession();
User u = new User();
u.setUsername("user1");
session.delete(u);
session.close();
}
I want to know why deletion does not work
try before session.close()
session.flush()
You are trying to delete non-managed entity that is not attached to session. In order to manipulate entity you should first attach it to session:
User u = (User) session.get(User.class, 1L);
session.delete(u);
Above is this sample of loading by id, so if you are restricted to username you have to write a more complex query.
I'm using Hibernate 4.2.6 with Java DB
Here's my
RegisterationHelper.java
org.hibernate.Transaction tx = session.beginTransaction();
String uid = std.getUserid();
System.out.println(uid);
Query query = session.createQuery("FROM university.Student");
List<Student> student = query.list();
for(Iterator it= student.iterator(); it.hasNext();)
{
//some code....
{
try
{
tx = session.beginTransaction();
int rgstnum=0;
Query q = session.createQuery("Select max(registrationnumber)from Student");
List currentRegNo = q.list();
rgstnum=(Integer)currentRegNo.get(0)+1;
std.setRegistrationnumber(rgstnum);
sc.setRegistrationnumber(rgstnum);
Serializable objID=session.save(std);
session.saveOrUpdate(sc);
tx.commit();
}
catch(Exception e)
{
}
//priniting sc.getRegistrationnumber() showing null
//priniting sc.getCurseid() has data
and RegistrationForm.java
#ManagedBean
#RequestScoped
public class RegistrationForm {
public String submitAction() {
RegistrationHelper rghp = new RegistrationHelper();
Student std = new Student();
std.setFirstname(getFirstName().toString());
std.setLastname(getLastName().toString());
std.setGender(getGender().toString());
std.setDob(getDateofBirth());
std.setAddress(getAddress().toString());
std.setPhone(getContactNumber().toString());
std.setEmail(getEmailID().toString());
std.setUserid(getUserID().toString());
std.setPassword(getPassword().toString());
Studentcourse sc = new Studentcourse();
sc.setCourseid(getCourse().toString());
String msg = rghp.insertStudent(std, sc);
if(msg.equals("error"))
{
setUserIdError("User Id already exist");
setUserID("");
return "Registration";
}
else
{
return "Success";
}
}`
So I think there is problem only with query Query q = session.createQuery("Select max(registrationnumber)from Student"); that doesn't retrieving registrationumber cause I'm able to store data in Student table if removing code regarding StudentCourse and other thing is getting Info: nested transactions not supported in sever log.
So please if my query is wrong or something else.
I do not think there are problems in the query: the message nested transactions not supported refers to the fact that you open the transaction (session.beginTransaction()) twice, one at the beginning and then again within the cycle. Try to remove the second.
I've created method to save entity with new id or update existing via hibernate session. When I use next code:
try {
Session session = sessionWrapper.getSession();
sessionWrapper.beginTransaction();
if (user.getId()==null || session.get(User.class, user.getId())==null) {
return (long) session.save(user);
} else {
session.get(User.class, user.getId());
session.merge(user);
return user.getId();
}
} finally {
sessionWrapper.commit();
sessionWrapper.closeSession();
}
it works ok, but when I use session.saveOrUpdate instead in case of new entity generated id is increased by two, not one. Why and how to fix it?
i am want output name of columns from table of my database on MySql. I am use Rest on Java, maven, tomcat, hibernate.
this code not work:
personDao.java:
public List<Person> getHeaders() {
List<Person> persons = null;
Session session = null;
try {
session = sessionFactory.openSession();
session.beginTransaction();
persons = session.createQuery("SHOW FIELDS FROM person").list();
session.getTransaction().commit();
} catch (Exception ex) {
if (session != null) {
session.getTransaction().rollback();
}
} finally {
if (session != null) {
session.close();
}
}
return persons;
}
service.java:
#GET
#Path("/getHeaders")
#Produces(MediaType.APPLICATION_JSON)
public List<Person> getHeaders() {
return personDao.getHeaders();
}
Please help me, how output name of columns ?
You can use the information_schema database and then use a standard hibernate query definition. In the information schema you can use a query as:
select * from COLUMNS WHERE table_name='person';
You can see this post: Get column name of property mapped with Hibernate
((Column) sessionFactoryBean.getConfiguration().getClassMapping(Person.class.getName())
.getProperty("myProperty").getColumnIterator().next()).getName();
and Get table column names in Hibernate