ТАК Я пытаюсь понять отношения между bean-компонентами и подключить свою программу к БД с помощью Hibernate.
Я получаю эту ошибку, я читаю некоторые другие вопросы и ответы на нее, но все еще не понимаю, как чтобы решить и почему это происходит.
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.thp.spring.simplecontext.entity.Bateau
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:780)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:758)
at com.thp.spring.simplecontext.dao.impl.BateauDAOImpl.create(BateauDAOImpl.java:31)
at com.thp.spring.simplecontext.main.AppJavaConfigMain.main(AppJavaConfigMain.java:14)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.thp.spring.simplecontext.entity.Bateau
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:124)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:773)
... 3 more
Я вижу причину root, но все еще не решаю проблему.
Вот файлы моего кода. Мои две сущности Муссейон и Бато:
package com.thp.spring.simplecontext.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "moussaillon")
public class Moussaillon {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "config")
private String config;
/*
* Many to one ralation This means that moussaillon entity will have a foreign
* key column named "bateau_id" referring to primary attribute id of entity
* bateau
*/
@ManyToOne
@JoinColumn(name = "bateau_id")
private Bateau bateau;
public Moussaillon() {
}
public Moussaillon(String firstName, String lastName, String config, Bateau bateau) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.config = config;
this.bateau = bateau;
}
//getters and setters are automatically created here
}
Вторая сущность здесь:
package com.thp.spring.simplecontext.entity;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "bateau")
public class Bateau {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "name")
private String nom;
@Column(name = "type")
private String type;
@Column(name = "size")
private double taille;
@OneToMany(mappedBy="bateau")
private List<Moussaillon> moussaillons;
public Bateau() {
}
public Bateau(int id, String nom, String type, double taille) {
super();
this.id = id;
this.nom = nom;
this.type = type;
this.taille = taille;
}
//getters and setters are automatically created here
}
У меня есть два интерфейса DAO, реализованных в соответствующих классах DAOIMpl.
package com.thp.spring.simplecontext.dao.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import com.thp.spring.simplecontext.dao.BateauDAO;
import com.thp.spring.simplecontext.entity.Bateau;
import com.thp.spring.simplecontext.entity.Moussaillon;
@Repository
public class BateauDAOImpl implements BateauDAO{
EntityManagerFactory emf=Persistence.createEntityManagerFactory("persistence");
EntityManager em=emf.createEntityManager();
@Override
public int create(int id, String name, String type, double taille) {
return 0;
}
@Override
public int create(Bateau bateau) {
em.persist(bateau);
return 0;
}
@Override
public Bateau update(Bateau bateau, String name, String type, double taille) {
// TODO Auto-generated method stub
return null;
}
@Override
public void delete(Bateau bateau) {
// TODO Auto-generated method stub
}
@Override
public Bateau findById(int id) {
// TODO Auto-generated method stub
return null;
}
@Override
public Bateau findByMoussaillon(Moussaillon moussaillon) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Bateau> findAll() {
// TODO Auto-generated method stub
return null;
}
}
Мой второй класс DAOImpl:
package com.thp.spring.simplecontext.dao.impl;
//al
@Repository
public class MoussaillonDAOImpl implements MoussaillonDAO {
EntityManagerFactory emf=Persistence.createEntityManagerFactory("persistence");
EntityManager em=emf.createEntityManager();
@Override
public int create(Moussaillon moussaillon) {
System.out.println("Starting Transaction");
em.getTransaction().begin();
em.persist(moussaillon);
return 0;
}
@Override
public Moussaillon update(Moussaillon moussaillon, String firstName, String lastName, String config) {
// TODO Auto-generated method stub
return null;
}
@Override
public void delete(Moussaillon moussaillon) {
// TODO Auto-generated method stub
}
@Override
public Moussaillon findById(int id) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Moussaillon> findAll() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Moussaillon> findAllByBateau(int bateauId) {
// TODO Auto-generated method stub
return null;
}
}
Мой основной класс
package com.thp.spring.simplecontext.main;
import com.thp.spring.simplecontext.dao.impl.BateauDAOImpl;
import com.thp.spring.simplecontext.dao.impl.MoussaillonDAOImpl;
import com.thp.spring.simplecontext.entity.Bateau;
import com.thp.spring.simplecontext.entity.Moussaillon;
public class AppJavaConfigMain {
public static voidmain(String[] args){
Bateau b1=new Bateau(3,"carthage","barque",10);
BateauDAOImpl b=new BateauDAOImpl();
b.create(b1);
Moussaillon m1 = new Moussaillon();
m1.setFirstName("gy");
m1.setLastName("yg");
m1.setConfig("java");
m1.setBateau(b1); //m1.setId(1);
MoussaillonDAOImpl mdao = new MoussaillonDAOImpl();
System.out.println("persist new moussaillon");
mdao.create(m1);
System.out.println("persist finished");
}
}
Я использую базу данных с именем bateaumoussaillonJDB C. В этой БД у меня есть две таблицы:
CREATE DATABASE bateaumoussaillonJDBC;
CREATE TABLE bateaumoussaillonJDBC.bateau(
id int NOT NULL,
name CHAR(80) NOT NULL,
type CHAR(80) NOT NULL,
size DOUBLE NOT NULL,
PRIMARY KEY(id)
)ENGINE=InnoDB;
CREATE TABLE bateaumoussaillonJDBC.moussaillon(
id int NOT NULL AUTO_INCREMENT,
first_name CHAR(80) NOT NULL,
last_name CHAR(80) NOT NULL,
config CHAR(80) NOT NULL,
bateau_id INT NOT NULL,
PRIMARY KEY(id),
CONSTRAINT FK_BateauMoussaillon FOREIGN KEY (bateau_id)
REFERENCES bateaumoussaillonJDBC.bateau(id)
)ENGINE=InnoDB;