vendredi 6 mars 2015

JPA find() works, persist no exceptions no results, remove shows querry and throw Removing a detached instance exception

I don't know what should I add to make it works. Here is my Entity class:



@Entity
public class Student {

@Id
@GeneratedValue
private int id;
private String name;
private int age;

//setters and getters
}


my application-context.xml:



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU"
xmlns:context="http://ift.tt/GArMu7"
xmlns:tx="http://ift.tt/OGfeU2"
xsi:schemaLocation="http://ift.tt/GArMu6
http://ift.tt/1jdM0fG
http://ift.tt/OGfeU2
http://ift.tt/1cQrvTl
http://ift.tt/GArMu7
http://ift.tt/QEDs1k">

<context:annotation-config />
<context:component-scan base-package="orm" />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="wisla666"/>
</bean>

<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="orm.entity" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>

<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf" />
</bean>

<tx:annotation-driven transaction-manager="txManager"/>


and this is my Dao class:



import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import orm.entity.Student;

@Repository
public class StudentDaoImpl implements StudentDao {

@PersistenceContext
private EntityManager entityManager;

@Override
public Student loadStudent(int id) {
return entityManager.find(Student.class, id);
}

@Override
public void saveStudent(Student student) {
entityManager.persist(student);
}

@Override
public void deleteStudent(Student student) {
entityManager.remove(entityManager.merge(student));
}
}


First I load Student object from DB and it works and then I try to remove this object from DB and it doesn't work. During removing the sql syntax is visible:



Hibernate: select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from Student student0_ where student0_.id=?


and an exception is thrown:



java.lang.IllegalArgumentException: Removing a detached instance orm.entity.Student#2


The question is what can I do to make it works?


Aucun commentaire:

Enregistrer un commentaire