主頁 > 區塊鏈 > 當嘗試通過它持久化物體時,ManyToMany關系的非擁有部分似乎不起作用

當嘗試通過它持久化物體時,ManyToMany關系的非擁有部分似乎不起作用

2021-12-28 12:50:34 區塊鏈

這可能看起來很長,但這是一個簡單的問題。其中大部分是標準樣板代碼,您無需閱讀,但我將其添加到此處,以防我在學習教程時出錯。

實際問題:我用粗體指定

我正在處理 2 個表的多對多關系:subjectsstudents. 我已經為多對多關系定義了資料庫模式subjectsstudents使用單獨的表subject_student

表架構如下:

create table subjects
(
    id   int          not null auto_increment,
    name varchar(100) not null unique,
    primary key (id)
);


create table students
(
    id          int          not null auto_increment,
    name        varchar(100) not null,
    passport_id int          not null unique,
    primary key (id),
    foreign key (passport_id) references passports (id)
);


create table subject_student
(
    subject_id int not null,
    student_id int not null,
    primary key (subject_id, student_id),
    foreign key (subject_id) references subjects (id),
    foreign key (student_id) references students (id)
);

物體如下:

@Entity
@Table(name = "students")
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(nullable = false, length = 100)
    private String name;

    @OneToOne(fetch = FetchType.LAZY)
    private Passport passport;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
            name = "subject_student",
            joinColumns = @JoinColumn(name = "student_id"), // join column on owning side
            inverseJoinColumns = @JoinColumn(name = "subject_id") // join column on other side
    )
    @ToString.Exclude
    private List<Subject> subjects = new ArrayList<>();

    // constructors
    
    public void addSubject(Subject subject) {
        subjects.add(subject);
    }

    public void removeSubject(Subject subject) {
        subjects.remove(subject);
    }
}

@Entity
@Table(name = "subjects")
public class Subject {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(nullable = false, length = 100, unique = true)
    private String name;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "subject")
    private List<Review> reviews = new ArrayList<>();

    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "subjects")
    @ToString.Exclude
    private List<Student> students = new ArrayList<>();

    public Subject(String name) {
        this.name = name;
    }

    public void addReview(Review review) {
        reviews.add(review);
    }

    public void addStudent(Student student) {
        students.add(student);
    }
}

現在問題來了:這里Student物體是擁有的部分。

我想將學生添加到特定主題。所以我做了以下事情:

@Transactional
public class SubjectRepository {

    @PersistenceContext
    EntityManager em;
    
    public void addStudentsToSubject(int subjectId, List<Student> students) {

        Subject subject = findById(subjectId);

        students.forEach(student -> {

            subject.addStudent(student);

            student.addSubject(subject);

            em.persist(student);

        });

        em.persist(subject);
    }
}

But when I run the code, it runs fine but in the end JPA Rollbacks. So when I see database, the joined table has no new rows. This happens only when I try to add students to subject i.e., trying to go through non-owning side. The proper way (adding subjects to students works fine. That too is very similar to this piece of code).

This leaves me confused.

Now I have a suspect: The join table is subject_student but according to convention it should've been student_subject. Is that the culprit?

Or is there any deeper reasons why this doesn't work?

I'm adding the driver code as well here.

@Test
@Transactional
public void test_addStudentsToSubject() {

    // adding students to non-owning side subject

    int subjectId = 10_002;

    Student s1 = studentRepository.findById(20_002);
    Student s2 = studentRepository.findById(20_003);
    List<Student> students = Arrays.asList(s1, s2);

    subjectRepository.addStudentsToSubject(subjectId, students);
}

@Test
@Transactional
public void getSubjectsAndStudent() {

    int id = 10_002;
    Subject subject = subjectRepository.findById(id);

    log.info("Subject = {}", subject);

    List<Student> students = subject.getStudents();
    log.info("Subject = {}, taken students = {}", subject, students);
}

EDIT: adding logs for first test:

2021-12-27 22:54:02.015  INFO 12352 --- [           main] s.l.j.r.relationship.ManyToManyTests     : Starting ManyToManyTests using Java 17 on Ahroo with PID 12352 (started by msi in E:\Code\Tutorials\jpa_hibernate)
2021-12-27 22:54:02.017  INFO 12352 --- [           main] s.l.j.r.relationship.ManyToManyTests     : No active profile set, falling back to default profiles: default
2021-12-27 22:54:02.551  INFO 12352 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-12-27 22:54:02.567  INFO 12352 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 9 ms. Found 0 JPA repository interfaces.
2021-12-27 22:54:03.047  INFO 12352 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-12-27 22:54:03.089  INFO 12352 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.3.Final
2021-12-27 22:54:03.209  INFO 12352 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-12-27 22:54:03.322  INFO 12352 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2021-12-27 22:54:03.615  INFO 12352 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2021-12-27 22:54:03.636  INFO 12352 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2021-12-27 22:54:04.258  INFO 12352 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-12-27 22:54:04.335  INFO 12352 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-12-27 22:54:05.102  INFO 12352 --- [           main] s.l.j.r.relationship.ManyToManyTests     : Started ManyToManyTests in 3.376 seconds (JVM running for 4.431)
2021-12-27 22:54:05.103  INFO 12352 --- [           main] s.l.j.JpaHibernateApplication            : ----------------------------------------------------------------------------------------------------------
2021-12-27 22:54:05.173  INFO 12352 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@2a225dd7 testClass = ManyToManyTests, testInstance = spring.learn.jpa_hibernate.repository.relationship.ManyToManyTests@155318b5, testMethod = test_addStudentsToSubject_Method2@ManyToManyTests, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@61eaec38 testClass = ManyToManyTests, locations = '{}', classes = '{class spring.learn.jpa_hibernate.JpaHibernateApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3d1cfad4, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@2e55dd0c, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@625732, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@4e096385, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@793be5ca, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@1554909b], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@41d53813]; rollback [true]
Hibernate: select student0_.id as id1_5_0_, student0_.name as name2_5_0_, student0_.passport_id as passport3_5_0_ from students student0_ where student0_.id=?
Hibernate: select student0_.id as id1_5_0_, student0_.name as name2_5_0_, student0_.passport_id as passport3_5_0_ from students student0_ where student0_.id=?
Hibernate: select subject0_.id as id1_7_0_, subject0_.name as name2_7_0_ from subjects subject0_ where subject0_.id=?
Hibernate: select subjects0_.student_id as student_1_6_0_, subjects0_.subject_id as subject_2_6_0_, subject1_.id as id1_7_1_, subject1_.name as name2_7_1_ from subject_student subjects0_ inner join subjects subject1_ on subjects0_.subject_id=subject1_.id where subjects0_.student_id=?
Hibernate: select subjects0_.student_id as student_1_6_0_, subjects0_.subject_id as subject_2_6_0_, subject1_.id as id1_7_1_, subject1_.name as name2_7_1_ from subject_student subjects0_ inner join subjects subject1_ on subjects0_.subject_id=subject1_.id where subjects0_.student_id=?
2021-12-27 22:54:05.435  INFO 12352 --- [           main] o.h.c.i.AbstractPersistentCollection     : HHH000496: Detaching an uninitialized collection with queued operations from a session: [spring.learn.jpa_hibernate.entity.relationship.Subject.students#10002]
2021-12-27 22:54:05.437  INFO 12352 --- [           main] i.StatisticalLoggingSessionEventListener : Session Metrics {
    482901 nanoseconds spent acquiring 1 JDBC connections;
    0 nanoseconds spent releasing 0 JDBC connections;
    15821999 nanoseconds spent preparing 5 JDBC statements;
    14897401 nanoseconds spent executing 5 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    0 nanoseconds spent performing 0 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;
    0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
    0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
}
2021-12-27 22:54:05.437  INFO 12352 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test: [DefaultTestContext@2a225dd7 testClass = ManyToManyTests, testInstance = spring.learn.jpa_hibernate.repository.relationship.ManyToManyTests@155318b5, testMethod = test_addStudentsToSubject_Method2@ManyToManyTests, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@61eaec38 testClass = ManyToManyTests, locations = '{}', classes = '{class spring.learn.jpa_hibernate.JpaHibernateApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3d1cfad4, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@2e55dd0c, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@625732, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@4e096385, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@793be5ca, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@1554909b], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]
2021-12-27 22:54:05.450  INFO 12352 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-12-27 22:54:05.452  INFO 12352 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2021-12-27 22:54:05.460  INFO 12352 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

logs for 2nd test (which retrieves modified values):

22:56:51.185 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}
2021-12-27 22:56:51.463  INFO 12240 --- [           main] s.l.j.r.relationship.ManyToManyTests     : Starting ManyToManyTests using Java 17 on Ahroo with PID 12240 (started by msi in E:\Code\Tutorials\jpa_hibernate)
2021-12-27 22:56:51.465  INFO 12240 --- [           main] s.l.j.r.relationship.ManyToManyTests     : No active profile set, falling back to default profiles: default
2021-12-27 22:56:51.996  INFO 12240 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-12-27 22:56:52.016  INFO 12240 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 12 ms. Found 0 JPA repository interfaces.
2021-12-27 22:56:52.507  INFO 12240 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-12-27 22:56:52.557  INFO 12240 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.3.Final
2021-12-27 22:56:52.683  INFO 12240 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-12-27 22:56:52.790  INFO 12240 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2021-12-27 22:56:53.099  INFO 12240 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2021-12-27 22:56:53.121  INFO 12240 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2021-12-27 22:56:53.781  INFO 12240 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-12-27 22:56:53.857  INFO 12240 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-12-27 22:56:54.656  INFO 12240 --- [           main] s.l.j.r.relationship.ManyToManyTests     : Started ManyToManyTests in 3.47 seconds (JVM running for 4.387)
2021-12-27 22:56:54.658  INFO 12240 --- [           main] s.l.j.JpaHibernateApplication            : ----------------------------------------------------------------------------------------------------------
2021-12-27 22:56:54.723  INFO 12240 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@2a225dd7 testClass = ManyToManyTests, testInstance = spring.learn.jpa_hibernate.repository.relationship.ManyToManyTests@37393dab, testMethod = getSubjectsAndStudent@ManyToManyTests, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@61eaec38 testClass = ManyToManyTests, locations = '{}', classes = '{class spring.learn.jpa_hibernate.JpaHibernateApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3d1cfad4, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@2e55dd0c, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@625732, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@4e096385, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@793be5ca, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@1554909b], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@4cbb11e4]; rollback [true]
Hibernate: select subject0_.id as id1_7_0_, subject0_.name as name2_7_0_ from subjects subject0_ where subject0_.id=?
2021-12-27 22:56:54.949  INFO 12240 --- [           main] s.l.j.r.relationship.ManyToManyTests     : Subject = Subject(id=10002, name=History)
Hibernate: select students0_.subject_id as subject_2_6_0_, students0_.student_id as student_1_6_0_, student1_.id as id1_5_1_, student1_.name as name2_5_1_, student1_.passport_id as passport3_5_1_ from subject_student students0_ inner join students student1_ on students0_.student_id=student1_.id where students0_.subject_id=?
2021-12-27 22:56:54.951  INFO 12240 --- [           main] s.l.j.r.relationship.ManyToManyTests     : Subject = Subject(id=10002, name=History), taken students = [Student(id=20001, name=Adam)]
2021-12-27 22:56:54.976  INFO 12240 --- [           main] i.StatisticalLoggingSessionEventListener : Session Metrics {
    497999 nanoseconds spent acquiring 1 JDBC connections;
    0 nanoseconds spent releasing 0 JDBC connections;
    18084498 nanoseconds spent preparing 2 JDBC statements;
    11998799 nanoseconds spent executing 2 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    0 nanoseconds spent performing 0 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;
    0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
    0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
}
2021-12-27 22:56:54.977  INFO 12240 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test: [DefaultTestContext@2a225dd7 testClass = ManyToManyTests, testInstance = spring.learn.jpa_hibernate.repository.relationship.ManyToManyTests@37393dab, testMethod = getSubjectsAndStudent@ManyToManyTests, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@61eaec38 testClass = ManyToManyTests, locations = '{}', classes = '{class spring.learn.jpa_hibernate.JpaHibernateApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3d1cfad4, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@2e55dd0c, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@625732, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@4e096385, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@793be5ca, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@1554909b], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]
2021-12-27 22:56:54.989  INFO 12240 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-12-27 22:56:54.991  INFO 12240 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2021-12-27 22:56:54.999  INFO 12240 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

uj5u.com熱心網友回復:

persist僅用于保存新物體。如果您findById使用了資料庫 id,這意味著該物體已經存在于資料庫中,因此您不需要持久化。

如果您嘗試持久化并且已經創建的物體,您應該得到一個EntityExistsException并且必須是回滾肇事者。

實際上,如果您將方法(或類)標記為@Transactional意味著在它結束時,如果沒有例外,物體更改將保留在資料庫中,而無需執行任何其他操作。

如果物體是在另一個 Persistence Context(即EntityManager實體)中獲得的,您應該使用merge它們將它們附加到當前的 Persistence Context。那看起來你Student的名單的情況

所以,你的方法應該是這樣的:

    public void addStudentsToSubject(int subjectId, List<Student> students) {
        Subject subject = findById(subjectId);
        students.forEach(student -> {
            em.merge(student);
            subject.addStudent(student);
            student.addSubject(subject);
        });
    }

更新

Spring 測驗默認回滾事務。只需添加@Rollback(false)到您的@Test應該就足夠了。您也可以在類級別添加它。

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/395403.html

標籤:mysql hibernate jpa

上一篇:如何使用休眠多對多從資料庫中獲取資料

下一篇:如何在@KafkaHandler中使用EntityManager/Hibernate事務

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • JAVA使用 web3j 進行token轉賬

    最近新學習了下區塊鏈這方面的知識,所學不多,給大家分享下。 # 1. 關于web3j web3j是一個高度模塊化,反應性,型別安全的Java和Android庫,用于與智能合約配合并與以太坊網路上的客戶端(節點)集成。 # 2. 準備作業 jdk版本1.8 引入maven <dependency> < ......

    uj5u.com 2020-09-10 03:03:06 more
  • 以太坊智能合約開發框架Truffle

    前言 部署智能合約有多種方式,命令列的瀏覽器的渠道都有,但往往跟我們程式員的風格不太相符,因為我們習慣了在IDE里寫了代碼然后打包運行看效果。 雖然現在IDE中已經存在了Solidity插件,可以撰寫智能合約,但是部署智能合約卻要另走他路,沒辦法進行一個快捷的部署與測驗。 如果團隊管理的區塊節點多、 ......

    uj5u.com 2020-09-10 03:03:12 more
  • 谷歌二次驗證碼成為區塊鏈專用安全碼,你怎么看?

    前言 谷歌身份驗證器,前些年大家都比較陌生,但隨著國內互聯網安全的加強,它越來越多地出現在大家的視野中。 比較廣泛接觸的人群是國際3A游戲愛好者,游戲盜號現象嚴重+國外賬號安全應用廣泛,這類游戲一般都會要求用戶系結名為“兩步驗證”、“雙重驗證”等,平臺一般都推薦用谷歌身份驗證器。 后來區塊鏈業務風靡 ......

    uj5u.com 2020-09-10 03:03:17 more
  • 密碼學DAY1

    目錄 ##1.1 密碼學基本概念 密碼在我們的生活中有著重要的作用,那么密碼究竟來自何方,為何會產生呢? 密碼學是網路安全、資訊安全、區塊鏈等產品的基礎,常見的非對稱加密、對稱加密、散列函式等,都屬于密碼學范疇。 密碼學有數千年的歷史,從最開始的替換法到如今的非對稱加密演算法,經歷了古典密碼學,近代密 ......

    uj5u.com 2020-09-10 03:03:50 more
  • 密碼學DAY1_02

    目錄 ##1.1 ASCII編碼 ASCII(American Standard Code for Information Interchange,美國資訊交換標準代碼)是基于拉丁字母的一套電腦編碼系統,主要用于顯示現代英語和其他西歐語言。它是現今最通用的單位元組編碼系統,并等同于國際標準ISO/IE ......

    uj5u.com 2020-09-10 03:04:50 more
  • 密碼學DAY2

    ##1.1 加密模式 加密模式:https://docs.oracle.com/javase/8/docs/api/javax/crypto/Cipher.html ECB ECB : Electronic codebook, 電子密碼本. 需要加密的訊息按照塊密碼的塊大小被分為數個塊,并對每個塊進 ......

    uj5u.com 2020-09-10 03:05:42 more
  • NTP時鐘服務器的特點(京準電子)

    NTP時鐘服務器的特點(京準電子) NTP時鐘服務器的特點(京準電子) 京準電子官V——ahjzsz 首先對時間同步進行了背景介紹,然后討論了不同的時間同步網路技術,最后指出了建立全球或區域時間同步網存在的問題。 一、概 述 在通信領域,“同步”概念是指頻率的同步,即網路各個節點的時鐘頻率和相位同步 ......

    uj5u.com 2020-09-10 03:05:47 more
  • 標準化考場時鐘同步系統推進智能化校園建設

    標準化考場時鐘同步系統推進智能化校園建設 標準化考場時鐘同步系統推進智能化校園建設 安徽京準電子科技官微——ahjzsz 一、背景概述隨著教育事業的快速發展,學校建設如雨后春筍,隨之而來的學校教育、管理、安全方面的問題成了學校管理人員面臨的最大的挑戰,這些問題同時也是學生家長所擔心的。為了讓學生有更 ......

    uj5u.com 2020-09-10 03:05:51 more
  • 位元幣入門

    引言 位元幣基本結構 位元幣基礎知識 1)哈希演算法 2)非對稱加密技術 3)數字簽名 4)MerkleTree 5)哪有位元幣,有的是UTXO 6)位元幣挖礦與共識 7)區塊驗證(共識) 總結 引言 上一篇我們已經知道了什么是區塊鏈,此篇說一下區塊鏈的第一個應用——位元幣。其實先有位元幣,后有的區塊 ......

    uj5u.com 2020-09-10 03:06:15 more
  • 北斗對時服務器(北斗對時設備)電力系統應用

    北斗對時服務器(北斗對時設備)電力系統應用 北斗對時服務器(北斗對時設備)電力系統應用 京準電子科技官微(ahjzsz) 中國北斗衛星導航系統(英文名稱:BeiDou Navigation Satellite System,簡稱BDS),因為是目前世界范圍內唯一可以大面積提供免費定位服務的系統,所以 ......

    uj5u.com 2020-09-10 03:06:20 more
最新发布
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:46:47 more
  • Hyperledger Fabric 使用 CouchDB 和復雜智能合約開發

    在上個實驗中,我們已經實作了簡單智能合約實作及客戶端開發,但該實驗中智能合約只有基礎的增刪改查功能,且其中的資料管理功能與傳統 MySQL 比相差甚遠。本文將在前面實驗的基礎上,將 Hyperledger Fabric 的默認資料庫支持 LevelDB 改為 CouchDB 模式,以實作更復雜的資料... ......

    uj5u.com 2023-04-16 07:28:31 more
  • .NET Core 波場鏈離線簽名、廣播交易(發送 TRX和USDT)筆記

    Get Started NuGet You can run the following command to install the Tron.Wallet.Net in your project. PM> Install-Package Tron.Wallet.Net 配置 public reco ......

    uj5u.com 2023-04-14 08:08:00 more
  • DKP 黑客分析——不正確的代幣對比率計算

    概述: 2023 年 2 月 8 日,針對 DKP 協議的閃電貸攻擊導致該協議的用戶損失了 8 萬美元,因為 execute() 函式取決于 USDT-DKP 對中兩種代幣的余額比率。 智能合約黑客概述: 攻擊者的交易:0x0c850f,0x2d31 攻擊者地址:0xF38 利用合同:0xf34ad ......

    uj5u.com 2023-04-07 07:46:09 more
  • Defi開發簡介

    Defi開發簡介 介紹 Defi是去中心化金融的縮寫, 是一項旨在利用區塊鏈技術和智能合約創建更加開放,可訪問和透明的金融體系的運動. 這與傳統金融形成鮮明對比,傳統金融通常由少數大型銀行和金融機構控制 在Defi的世界里,用戶可以直接從他們的電腦或移動設備上訪問廣泛的金融服務,而不需要像銀行或者信 ......

    uj5u.com 2023-04-05 08:01:34 more
  • solidity簡單的ERC20代幣實作

    // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; import "hardhat/console.sol"; //ERC20 同質化代幣,每個代幣的本質或性質都是相同 //ETH 是原生代幣,它不是ERC20代幣, ......

    uj5u.com 2023-03-21 07:56:29 more
  • solidity 參考型別修飾符memory、calldata與storage 常量修飾符C

    在solidity語言中 參考型別修飾符(參考型別為存盤空間不固定的數值型別) memory、calldata與storage,它們只能修飾參考型別變數,比如字串、陣列、位元組等... memory 適用于方法傳參、返參或在方法體內使用,使用完就會清除掉,釋放記憶體 calldata 僅適用于方法傳參 ......

    uj5u.com 2023-03-08 07:57:54 more
  • solidity注解標簽

    在solidity語言中 注釋符為// 注解符為/* 內容*/ 或者 是 ///內容 注解中含有這幾個標簽給予我們使用 @title 一個應該描述合約/介面的標題 contract, library, interface @author 作者的名字 contract, library, interf ......

    uj5u.com 2023-03-08 07:57:49 more
  • 評價指標:相似度、GAS消耗

    【代碼注釋自動生成方法綜述】 這些評測指標主要來自機器翻譯和文本總結等研究領域,可以評估候選文本(即基于代碼注釋自動方法而生成)和參考文本(即基于手工方式而生成)的相似度. BLEU指標^[^?88^^?^]^:其全稱是bilingual evaluation understudy.該指標是最早用于 ......

    uj5u.com 2023-02-23 07:27:39 more
  • 基于NOSTR協議的“公有制”版本的Twitter,去中心化社交軟體Damus

    最近,一個幽靈,Web3的幽靈,在網路游蕩,它叫Damus,這玩意詮釋了什么叫做病毒式營銷,滑稽的是,一個Web3產品卻在Web2的產品鏈上瘋狂傳銷,各方大佬紛紛為其背書,到底發生了什么?Damus的葫蘆里,賣的是什么藥? 注冊和簡單實用 很少有什么產品在用戶注冊環節會有什么噱頭,但Damus確實出 ......

    uj5u.com 2023-02-05 06:48:39 more