Java Spring JPA 数据库.表之间的连接 [英] Java Spring JPA DB. Connections between tables

查看:34
本文介绍了Java Spring JPA 数据库.表之间的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在表格接线方面遇到一些问题.我需要每个用户的 uniq 购物车,我将在其中存放书籍.

Get some problems with tables wiring. I need for each user uniq cart, where i will store books.

我无法理解如何使用 OneToMany/ManyToOne 以及整个画面应该是什么样子.

I can't understand how to work with OneToMany/ManyToOne and how the whole picture should look like.

当我在数据库中打开 AppUser 表时,cart_id"列始终为空.

When I open AppUser table in DB, "cart_id" column is always null.

购物车表只有 id 列 - 不确定是否应该这样

Cart table has only id column - not sure if it should be this way

谢谢!

@Component
@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
@Entity
public class AppUser implements UserDetails {

    @Id
    @SequenceGenerator(
            name = "user_sequence",
            sequenceName = "user_sequence",
            allocationSize =  1
    )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "user_sequence"
    )
    private Long id;

    @NotEmpty(message = "Name cannot be empty")
    private String firstName;

    @Email
    private String email;

    @NotEmpty
    private String password;

    @Enumerated(EnumType.STRING)
    private AppUserRole appUserRole;

    private Boolean locked = false;
    private Boolean enabled = false;

    @OneToOne
    @Autowired
    private Cart cart;


    public AppUser(String firstName, String email, String password, AppUserRole appUserRole) {
        this.firstName = firstName;
        this.email = email;
        this.password = password;
        this.appUserRole = appUserRole;
    }


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        SimpleGrantedAuthority authority = new SimpleGrantedAuthority(appUserRole.name());
        return Collections.singleton(authority);
    }

    @Override
    public String getPassword(){
        return password;
    }

    @Override
    public String getUsername() {
        return email;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return !locked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}

购物车

@Entity
@Component
public class Cart {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToMany
    @JoinColumn( name = "books_in_cart")
    private final List<Book> books;

    public Cart(){
        books = new ArrayList<Book>();
    }

    public List<Book> getBooks() {
        return books;
    }

    public void setBook(Book book){
        books.add(book);
    }
}

预订

@Setter
@Getter
@NoArgsConstructor
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotEmpty(message = "Book's title cannot be empty")
    @Size(min = 3, max = 100, message = "Book's title's length should be from 3 to 100")
    private String name;
    @NotEmpty(message = "Book's author name cannot be empty")
    @Size(min = 3, max = 100, message = "Book's author's name should be from 3 to 100")
    private String author;
    @NotEmpty(message = "Book's publisher cannot be empty")
    @Size(min = 3, max = 100, message = "Book's publisher's name should be from 3 to 100")
    private String publisher;
    @Min(value = 1000, message = "Book publishing year cannot be less than 1000")
    @Max(value = 2021, message = "Book publishing year cannot be more than 2021")
    private int    year;
    @NotEmpty(message = "Book's description cannot be empty")
    @Size(min = 1, max = 100, message = "Book's description's length cannot be more than 1000")
    private String plot;

    public Book(String name, String author, String publisher, int year, String plot) {
        this.name = name;
        this.author = author;
        this.publisher = publisher;
        this.year = year;
        this.plot = plot;
    }
}

推荐答案

我不包括任何验证注释,但您需要做的是以下内容:

I am not including any validation annotations but what you need to do is the following:

对于 AppUser 类:

@Table(name = "users")
@Entity
@Data
public class AppUser {

    @Id
    @SequenceGenerator(name = "user_sequence", sequenceName = "user_sequence", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_sequence")
    private Long id;

    private String firstName;

    private String email;

    private String password;

    @Enumerated(EnumType.STRING)
    private AppUserRole appUserRole;

    private Boolean locked;

    private Boolean enabled;

    @ToString.Exclude
    @EqualsAndHashCode.Exclude
    @OneToOne(mappedBy = "appUser", cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
    private Cart cart;

}

对于 Cart 类:

@Table(name = "carts")
@Entity
@Data
public class Cart {

    @Id
    private Long id;

    @ToString.Exclude
    @EqualsAndHashCode.Exclude
    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private AppUser appUser;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "cart_id")
    private Set<Book> books = new HashSet<>();

}

最后是 Book 类:

@Data
@Entity
@Table(name = "books")
public class Book {

    @Id
    @GeneratedValue(generator = "book_sequence", strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = "book_sequence", sequenceName = "book_sequence", allocationSize = 1)
    private Long id;

    private String name;

    private String author;

    private String publisher;

    private String plot;

}

您可以看到 AppUser 对象与 Cart 对象具有 一对一 关系,后者又具有单向 一对多Book的关系.

You can see that the AppUser object has a one-to-one relation with the Cart object which in turn has a unidirectional one-to-many relation with Book.

希望能帮到你.

这篇关于Java Spring JPA 数据库.表之间的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆