gpt4 book ai didi

java - 在 OneToMany 的情况下不会发生数据库插入

转载 作者:行者123 更新时间:2023-12-02 01:30:36 25 4
gpt4 key购买 nike

我想使用 @OneToMany 关系在数据库中插入数据,但它不起作用。

我有两个表,其架构如下:

创建表讲师(Id int 主键,姓名 varchar2(50),Email varchar2(15));

创建表类(class)(Course_Id int 主键,Course_Name Varchar2(20) NOT NULL Unique,Instructor_Id int ,外键(Instructor_Id)引用讲师(Id));

当我尝试插入数据库时​​,它没有给我任何错误,但在数据库中它没有反射(reflect)两个表

类(class):


@Entity
@Table(name = "Courses")
public class Courses {

@Id
@Column(name = "Course_Id ")
private int courseId;

@Column(name = "Course_Name")
private String courseName;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "Instructor_Id")
private Instructor instructor;

public int getCourseId() {
return courseId;
}

public void setCourseId(int courseId) {
this.courseId = courseId;
}

public String getCourseName() {
return courseName;
}

public void setCourseName(String courseName) {
this.courseName = courseName;
}

public Instructor getInstructor() {
return instructor;
}

public void setInstructor(Instructor instructor) {
this.instructor = instructor;
}

}

导师:

@Entity
@Table(name = "Instructor")
public class Instructor {

@Id
@Column(name = "Id")
private int id;

@Column(name = "Name")
private String name;

@Column(name = "Email")
private String email;

@OneToMany(mappedBy = "instructor", cascade = CascadeType.ALL)
private List<Courses> courses;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public List<Courses> getCourses() {
return courses;
}

public void setCourses(List<Courses> courses) {
this.courses = courses;
}

public void setEmail(String string) {
this.email = string;
}


主类:

public class HibernateTest {

public static void main(String[] args) {

try (SessionFactory factory = new Configuration().configure("hibernate.cfg.xml")
.addAnnotatedClass(Courses.class).addAnnotatedClass(Instructor.class).buildSessionFactory();) {


//Test Insert
Instructor i1 = new Instructor();
i1.setEmail("test@mail.com");
i1.setId(100);
i1.setName("patcyy");

//List Of Courses
List<Courses> listOfCourses = new ArrayList<>();

Courses c1 = new Courses();
c1.setCourseName("Java");
c1.setCourseId(1);

Courses c2 = new Courses();
c2.setCourseName("C");
c2.setCourseId(2);

listOfCourses.add(c1);
listOfCourses.add(c2);

//adding to instructor
i1.setCourses(listOfCourses);

//insert in DB
inserIntoDb(factory, i1);

} catch (Exception e) {
System.out.println("Exception : " + e);
}

}

/**
*
* @param factory
* @param st
*/
private static void inserIntoDb(SessionFactory factory, Instructor st) {

System.out.println("Inserting into DB");

Session session = factory.getCurrentSession();

session.beginTransaction();

session.save(st);

session.getTransaction().commit();

}
}

日志:



May 13, 2019 8:35:24 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.2.Final}
May 13, 2019 8:35:25 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
May 13, 2019 8:35:25 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
May 13, 2019 8:35:25 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [oracle.jdbc.driver.OracleDriver] at URL [jdbc:oracle:thin:@localhost:1521:****]
May 13, 2019 8:35:25 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=****, password=****}
May 13, 2019 8:35:25 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
May 13, 2019 8:35:25 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
May 13, 2019 8:35:25 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle12cDialect
Inserting into DB
Hibernate: select courses_.Course_Id, courses_.Course_Name as Course_Name2_0_, courses_.Instructor_Id as Instructor_Id3_0_ from Courses courses_ where courses_.Course_Id=?
Hibernate: select courses_.Course_Id, courses_.Course_Name as Course_Name2_0_, courses_.Instructor_Id as Instructor_Id3_0_ from Courses courses_ where courses_.Course_Id=?
Hibernate: insert into Instructor (Email, Name, Id) values (?, ?, ?)

更新的代码:

package com.patcyy.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateTest {

public static void main(String[] args) {

try (SessionFactory factory = new Configuration().configure("hibernate.cfg.xml")
.addAnnotatedClass(Courses.class).addAnnotatedClass(Instructor.class).buildSessionFactory();) {


//Test Insert
Instructor i1 = new Instructor();
i1.setEmail("test@mail.com");
i1.setId(100);
i1.setName("patcyy");

//List Of Courses
List<Courses> listOfCourses = new ArrayList<>();

Courses c1 = new Courses();
c1.setCourseName("Java");
c1.setCourseId(1);
c1.setInstructor(i1);

Courses c2 = new Courses();
c2.setCourseName("C");
c2.setCourseId(2);
c2.setInstructor(i1);

listOfCourses.add(c1);
listOfCourses.add(c2);

//adding to instructor
i1.setCourses(listOfCourses);

//insert in DB
inserIntoDb(factory, i1);

} catch (Exception e) {
System.out.println("Exception : " + e);
}

}

/**
*
* @param factory
* @param st
*/
private static void inserIntoDb(SessionFactory factory, Instructor st) {

System.out.println("Inserting into DB");

Session session = factory.getCurrentSession();

session.beginTransaction();

session.save(st);

session.getTransaction().commit();

}
}

调试成功。

Debug

配置:


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<!-- JDBC Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:patcyy</property>
<property name="connection.username">SYSTEM</property>
<property name="connection.password">patcyy</property>

<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>

<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle12cDialect</property>

<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>

<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>

</session-factory>

</hibernate-configuration>

最佳答案

@Entity
@Table(name = "Instructor")
public class Instructor {

@OneToMany(mappedBy = "instructor", cascade = CascadeType.ALL)
private List<Courses> courses;
}

这里的ma​​ppedBy表示Courses中的instructor用于维护InstructorCourses 关系。 Hibernate 将根据该值而不是 Instructor 中的 course 更新此关系的相关外键值。

您正在做的是在 Instructor 中设置 course 的值,而不是在 Courses 中设置 instructor ,这就是为什么他们的关系永远不会更新。您必须在类(class)中设置instructor的值:

Courses c1 = new Courses();
c1.setCourseName("Java");
c1.setCourseId(1);
c1.setInstructor(i1);

关于java - 在 OneToMany 的情况下不会发生数据库插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56105370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com