我正在尝试使用JPA创建一个与数据库交互的后端论坛。我现在面临的问题是实体之间的关系。我有3个(至少目前为止)但是当我尝试使用JPA工具创建表时,它并没有创建它们,这让我觉得关系有问题。任何人都可以帮助我吗?
@Entity
@Table(name="users")
public class UserModel {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private long user_id;
private String name;
private String email;
@OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST,CascadeType.MERGE})
private ArrayList<TopicoModel> myTopics = new ArrayList<TopicoModel>();
@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST,CascadeType.MERGE})
private ArrayList<TopicoModel> myFavTopics = new ArrayList<TopicoModel>();
-
@Entity
@Table(name="topics")
public class TopicModel{
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private long topic_id;
@OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST,CascadeType.MERGE})
private ArrayList<PostModel> comments;
@ManyToOne(cascade = CascadeType.MERGE)
private UserModel author;
-
@Entity
@Table(name="posts")
public class PostModel {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private long post_id;
private String message;
private int likes = 0;
private int dislikes = 0;
@OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST,CascadeType.MERGE})
private ArrayList<UserModel> agrees;
@OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST,CascadeType.MERGE})
private ArrayList<UserModel> thanks;
EDIT1: 当我尝试使用一些测试数据填充数据库时,它会给我以下错误:
Internal Exception: java.sql.SQLException: Field 'myTopics_TOPIC_ID' doesn't have a default value
Error Code: 1364
Call: INSERT INTO users_topics (myFavTopics_TOPIC_ID, UserModel_USER_ID) VALUES (?, ?)
bind => [2 parameters bound]
Query: DataModifyQuery(name="topicos_favoritos" sql="INSERT INTO users_topics (myFavTopics_TOPIC_ID, UserModel_USER_ID) VALUES (?, ?)")
EDIT2: 我已经尝试添加一个默认值,但它给了我相同的错误,但使用“myFavTopics”变量。 以下是填充db:
的代码UserModel u1 = new UserModel();
u1.setEmail("asd@asd.pt");
u1.setName("A");
UserModel u2 = new UserModel();
u2.setEmail("qwer@qwer.pt");
u2.setName("B");
PostModel p1 = new PostModel("message 1", 0, 0);
PostModel p2 = new PostModel("message 2", 10, 0);
PostModel p3 = new PostModel("message 3", 0, 20);
ArrayList<PostModel> commentP1 = new ArrayList<PostModel>();
commentP1.add(p1);
commentP1.add(p3);
ArrayList<PostModel> commentP2 = new ArrayList<PostModel>();
commentP2.add(p2);
TopicModel t1 = new TopicModel(commentP1, u1);
TopicModel t2 = new TopicModel(commentP2, u2);
u1.addMyTopic(t1);
u2.addMyTopic(t2);
u1.addMyFavTopic(t2);
UserModel u3 = new UserModel();
u3.setEmail("yujy@yj.pt");
u3.setName("C");
JPAEntityManager factory = new JPAEntityManager();
EntityManager em = factory.getEntityManager();
em.getTransaction().begin();
em.persist(t1);
em.persist(t2);
em.persist(p1);
em.persist(p2);
em.persist(p3);
em.persist(u1);
em.persist(u2);
em.persist(u3);
em.getTransaction().commit();