Eclipselink Jpa 之 映射类型(多对一)
技术:Eclipselink Jpa + Lombok +mysql8.0.13
package com.atsico.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.persistence.*;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int c_id;
private String c_name;
@ManyToOne
private Stu stu;
}
package com.atsico.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class Stu {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int s_id;
private String s_name;
}
<?xml version="1.0" encoding="UTF-8"?> org.eclipse.persistence.jpa.PersistenceProvider com.atsico.pojo.Course com.atsico.pojo.Stu <properties>
<!-- 连接数据库的基本信息 -->
<property name="javax.persistence.jdbc.driver"
value="com.mysql.cj.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/jpadb?useSSL=false&serverTimezone=Asia/Shanghai"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password"
value="root"/>
<property name="eclipselink.logging.level" value="all"/>
<property name="eclipselink.ddl-generation"
value="create-or-extend-tables"/>
<property name="eclipselink.show_sql" value="true"/>
</properties>
</persistence-unit>
package com.atsico.service;
import com.atsico.pojo.Course;
import com.atsico.pojo.LibraryPojo;
import com.atsico.pojo.Stu;
import com.atsico.pojo.StudentPojo;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.LinkedList;
public class Jpa_Mapping_Test {
@Test
public void test_many2one() {
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("myPersistUnit");
EntityManager em = emf.createEntityManager();
EntityTransaction ts = em.getTransaction();
ts.begin();
/******************************************主体部分********************************************/
Stu stu = new Stu();
stu.setS_id(1);
stu.setS_name("Tom");
em.persist(stu);
Course c1 = new Course();
c1.setC_id(101);
c1.setC_name("Math");
c1.setStu(stu);
Course c2 = new Course();
c2.setC_id(102);
c2.setC_name("English");
c2.setStu(stu);
em.persist(c1);
em.persist(c2);
/******************************************主体部分********************************************/
ts.commit();
em.close();
emf.close();
}
}
运行正常