-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 5 posts ] 
Author Message
 Post subject: I need help to update an entity
PostPosted: Fri Jul 08, 2011 4:34 pm 
Newbie

Joined: Fri Jul 08, 2011 3:57 pm
Posts: 4
hi, i got 2 entities, Student and Phone, and a relationship one-to-many between them.

Code:
@Entity 
@Table(name = "STUDENT") 
public class Student { 
 
    private long studentId; 
    private String studentName; 
    private Set<Phone> studentPhoneNumbers = new HashSet<Phone>(0); 
 
    public Student() { 
    } 
 
    public Student(String studentName, Set<Phone> studentPhoneNumbers) { 
        this.studentName = studentName; 
        this.studentPhoneNumbers = studentPhoneNumbers; 
    } 
 
    @Id 
    @GeneratedValue 
    @Column(name = "STUDENT_ID") 
    public long getStudentId() { 
        return this.studentId; 
    } 
 
    public void setStudentId(long studentId) { 
        this.studentId = studentId; 
    } 
 
    @Column(name = "STUDENT_NAME", nullable = false, length = 100) 
    public String getStudentName() { 
        return this.studentName; 
    } 
 
    public void setStudentName(String studentName) { 
        this.studentName = studentName; 
    } 
 
    @OneToMany (mappedBy="student", cascade = CascadeType.ALL)       
 
    public Set<Phone> getStudentPhoneNumbers() { 
        return this.studentPhoneNumbers; 
    } 
 
    public void setStudentPhoneNumbers(Set<Phone> studentPhoneNumbers) { 
        this.studentPhoneNumbers = studentPhoneNumbers; 
    } 
   



Code:
@Entity 
@Table(name = "PHONE") 
public class Phone { 
 
    private long phoneId; 
    private String phoneType; 
    private String phoneNumber; 
 
    private Student student; 
    private Set<Student> students = new HashSet<Student>(0); 
     
    public Phone() { 
    } 
 
    public Phone(String phoneType, String phoneNumber) { 
        this.phoneType = phoneType; 
        this.phoneNumber = phoneNumber; 
    } 
     
    @Id 
    @GeneratedValue 
    @Column(name = "PHONE_ID") 
    public long getPhoneId() { 
        return this.phoneId; 
    } 
 
    public void setPhoneId(long phoneId) { 
        this.phoneId = phoneId; 
    } 
 
    @Column(name = "PHONE_TYPE", nullable = false, length=10) 
    public String getPhoneType() { 
        return this.phoneType; 
    } 
 
    public void setPhoneType(String phoneType) { 
        this.phoneType = phoneType; 
    } 
     
    @Column(name = "PHONE_NUMBER", nullable = false, length=15) 
    public String getPhoneNumber() { 
        return this.phoneNumber; 
    } 
 
    public void setPhoneNumber(String phoneNumber) { 
        this.phoneNumber = phoneNumber; 
    } 
     
    @ManyToOne(cascade = CascadeType.ALL) 
    @JoinColumn (name="STUDENT_ID") 
    public Student getStudent() { 
        return this.student; 
    } 
 
    public void setStudent(Student student) { 
        this.student = student; 
    } 


here is the code of applicationContext.xml:

Code:
    ... 
     <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">   
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>   
            <property name="url" value="jdbc:mysql://localhost/Project"/>   
            <property name="username" value="root"/>   
            <property name="password" value="root"/>   
        </bean>   
           
        <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">   
            <property name="dataSource" ref="myDataSource" />   
            <property name="annotatedClasses">   
                <list>   
                    <value>com.domain.Student</value>                         
                    <value>com.domain.Phone</value>                           
                </list>   
            </property>   
            <property name="hibernateProperties">   
                <props>   
                    <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>   
                    <prop key="hibernate.show_sql">true</prop>   
                    <prop key="hibernate.hbm2ddl.auto">create</prop>   
                </props>   
            </property>   
        </bean>   
     
     <bean id="myClassDAO" class="com.project.dao.ClassDAOImpl"> 
            <property name="sessionFactory" ref="mySessionFactory"/> 
     </bean>   
     
    ... 


And my ClassDAOImpl looks like:

Code:
    public class ClassDAOImpl{ 
     
    private HibernateTemplate hibernateTemplate; 
    private Session session; 
    public void setSessionFactory(SessionFactory sessionFactory) { 
            this.hibernateTemplate = new HibernateTemplate(sessionFactory); 
            this.session = sessionFactory.openSession(); 
    }     
     
    public void updateStudent(){ 
           
            Transaction transaction = session.beginTransaction();           
            Student s = (Student)session.get(Student.class, new Long(1));   
            Set<Phone> phoneNumbers =s.getStudentPhoneNumbers();   
            phoneNumbers.add(new Phone ("house","12342342"));   
            s.setStudentPhoneNumbers(phoneNumbers);   
            session.update(s);   
            transaction.commit(); 
             
    } 
     



I just want to add a phone to the student with primary key "1". For this purpose, first I get the student and then I update the phone set by adding a new one. Finally I update the entity Student.
I looked at my Phone table, and there was a new row with the new phone, but the foreign key (STUDENT_ID) appeared with "Null" value, therefore the relationship is not registered. How could i fix it?

Thanks in advance

Edit: I've already solved the issue, just adding this line of code
Code:
phone.setStudent(s);


What i'm wondering now, is if i'm getting the session and managing transactions properly. I've noticed that if I close the session after commit the transaction i can only execute the method updateStudent once, the second time i do, hibernate says that the connection is closed. Please, tell me if my code is correct.


Top
 Profile  
 
 Post subject: Re: I need help to update an entity
PostPosted: Sat Jul 09, 2011 7:23 am 
Newbie

Joined: Tue Sep 23, 2003 7:02 am
Posts: 16
Hi

I think that the way you are handling the transactions could be better. Is your project a student project?

I am guessing from the code it is.

What I would do if I was you is to look at the Spring framework. It supports Hibernate and handles a lot of the hibernate boiler plate code
for you.

Since you already understand the concept of a DAO I think you will find Springs support very helpful.

Lee


Top
 Profile  
 
 Post subject: Re: I need help to update an entity
PostPosted: Sat Jul 09, 2011 3:22 pm 
Newbie

Joined: Fri Jul 08, 2011 3:57 pm
Posts: 4
leetcooper wrote:
Hi

I think that the way you are handling the transactions could be better. Is your project a student project?

I am guessing from the code it is.

What I would do if I was you is to look at the Spring framework. It supports Hibernate and handles a lot of the hibernate boiler plate code
for you.

Since you already understand the concept of a DAO I think you will find Springs support very helpful.

Lee


Yes, it is a student project. I'm really messed up with this... If i use hibernateTemplate instead of session, is my code right?
Anyway i can't use hibernateTemplate, i get the following error:

Code:
failed to lazily initialize a collection of role: com.pfc.domain.Student.studentPhoneNumbers, no session or session was closed 
org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383) 
    org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375) 
    org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:368) 
    org.hibernate.collection.PersistentSet.add(PersistentSet.java:212) 
...


I read the spring documentation, I put @Transactional above updateStudent() method, and declared the bean:
Code:
    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
          <property name="sessionFactory" ref="mySessionFactory" />
   </bean>



Then I try to get a session using sessionFactory.getCurrentSession() but it didn't work.

Could someone add a few lines of code to my code to make it work? I have not much time to build the application... I'd greatly appreciate your help.


Top
 Profile  
 
 Post subject: Re: I need help to update an entity
PostPosted: Sun Jul 10, 2011 6:32 am 
Newbie

Joined: Tue Sep 23, 2003 7:02 am
Posts: 16
This is the bit you are missing..
Code:
    <tx:advice id="txAdvice" transaction-manager="transactionManager">

        <tx:attributes>

            <tx:method name="add*" propagation="REQUIRED" />

            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="*" propagation="SUPPORTS" read-only="true"/>

        </tx:attributes>

    </tx:advice>

   

    <aop:config>

        <aop:advisor

            pointcut="execution(* *..StudentService.*(..))"

            advice-ref="txAdvice" />

    </aop:config>



But you should also have a structure like this

Service Interfaces -> Service Implementation -> DAO Interface -> DAO Implementation

Code:
public interface GenericDAOInterface<T>
{
    public void save(T object);
    public T get(Integer id);
    public void update(T object);
    public void delete(T object);
}

public interface StudentDAOInterface extends GenericDAOInterface<RSS>
{

}

public class StudentDAOHibernateImpl extends HibernateDaoSupport implements StudentDAOInterface{

    public void save(Student student) {
        getHibernateTemplate().save(student);
    }

    public Student get(Integer id) {
        return (Student)getHibernateTemplate().get(Student.class, id);
    }

    public void update(Student object) {
        getHibernateTemplate().update(student);
    }

}


public interface StudentService
{
    public void registerStudent(Student student);
}


public class StudentServiceImpl implements StudentService
{
    private StudentDAOInterface studentDAO;

    public void registerStudent(Student student) {
       studentDAO.save(student);
    }

    // use Spring to inject
    public void setStudentDAO(StudentDAOInterface studentDAO)
    {
        this.studentDAO = studentDAO;
    }
}


Lee


Top
 Profile  
 
 Post subject: Re: I need help to update an entity
PostPosted: Mon Jul 11, 2011 12:49 pm 
Newbie

Joined: Fri Jul 08, 2011 3:57 pm
Posts: 4
leetcooper wrote:
This is the bit you are missing..
Code:
    <tx:advice id="txAdvice" transaction-manager="transactionManager">

        <tx:attributes>

            <tx:method name="add*" propagation="REQUIRED" />

            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="*" propagation="SUPPORTS" read-only="true"/>

        </tx:attributes>

    </tx:advice>

   

    <aop:config>

        <aop:advisor

            pointcut="execution(* *..StudentService.*(..))"

            advice-ref="txAdvice" />

    </aop:config>



But you should also have a structure like this

Service Interfaces -> Service Implementation -> DAO Interface -> DAO Implementation

Code:
public interface GenericDAOInterface<T>
{
    public void save(T object);
    public T get(Integer id);
    public void update(T object);
    public void delete(T object);
}

public interface StudentDAOInterface extends GenericDAOInterface<RSS>
{

}

public class StudentDAOHibernateImpl extends HibernateDaoSupport implements StudentDAOInterface{

    public void save(Student student) {
        getHibernateTemplate().save(student);
    }

    public Student get(Integer id) {
        return (Student)getHibernateTemplate().get(Student.class, id);
    }

    public void update(Student object) {
        getHibernateTemplate().update(student);
    }

}


public interface StudentService
{
    public void registerStudent(Student student);
}


public class StudentServiceImpl implements StudentService
{
    private StudentDAOInterface studentDAO;

    public void registerStudent(Student student) {
       studentDAO.save(student);
    }

    // use Spring to inject
    public void setStudentDAO(StudentDAOInterface studentDAO)
    {
        this.studentDAO = studentDAO;
    }
}


Lee


Thanks Lee, I tried but i got a lot of errors... I don't want to change the structure because it would take me a long time, and as I said I have not much time... do you think it is absolutely necessary to change the way I handle the sessions and transactions?


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 5 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.