简体   繁体   中英

java hibernate : save with join column not working

User.java

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    
    private String name;
    // Getter & Setter
}

Log.java

@Entity
public class Log {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @OneToOne(cascade = CascadeType.MERGE)
    @JoinColumn(name = "user_id", referencedColumnName = "id", insertable = false, updatable = false)
    private Processor processor;

    // Getter & Setter
}

Controller.js

        User user = userRepository.findById(1).get();

        Log log = new Log();
        log.setUser(user);
        logRepository.save(log);

Now, Log record is created in MySQL db, but, user_id field is null.

How I can fix this?

You have insertable = false, updatable = false set that tells Hibernate not to save. Remove this.

Checkout the API doc https://javaee.github.io/javaee-spec/javadocs/javax/persistence/JoinColumn.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM