在上一篇《自定义配置LINQ的ORM实体类》中,收到某位博友的指正,改变了自己对某些东西的看法。其中最重要的一点便是:不轻易评判他人,专心做好自己。望与大家共勉。
今天使用做一个最简单的Demo,为自己和初学者提供一个参考。但是各种注解的说明和具体使用环境,还需每个人自己进行细致学习。
数据库还是使用上一章的,表就是简单的学生和班级。
首先建立实体类 班级
1 import java.io.Serializable;
2 import java.util.Set;
3 import javax.persistence.CascadeType;
4 import javax.persistence.Column;
5 import javax.persistence.Entity;
6 import javax.persistence.FetchType;
7 import javax.persistence.Id;
8 import javax.persistence.OneToMany;
9 import javax.persistence.Table;
10
11
12 @Entity
13 @Table(name="MyClass")
14 public class MyClass implements Serializable {
15
16 /**
17 * 序列化ID
18 */
19 private static final long serialVersionUID = 1L;
20
21 /**
22 * 班级编号
23 * @Id 表示主键
24 * @Column 设置相对应的列参数
25 * 因为不是自增长的主键,所以使用 GeneratedValue 注解会报错
26 */
27 @Id
28 @Column(name="class_no",nullable=false)
29 private String classNo;
30
31 @Column(name="class_name",nullable=false)
32 private String className;
33
34 /**
35 * 设置一对多关系,表示该是主键表
36 * mappedBy 表示被映射在属性在多方实体中的字段,
37 * cascade 表示维护关系由谁来进行,可以进行哪些维护
38 */
39 @OneToMany(targetEntity=Student.class,mappedBy="myClass",fetch=FetchType.EAGER,cascade=CascadeType.ALL)
40 private Set<Student> student;
41
42
43 public Set<Student> getStudent() {
44 return student;
45 }
46
47 public void setStudent(Set<Student> student) {
48 this.student = student;
49 }
50
51 public String getClassNo() {
52 return classNo;
53 }
54
55 public void setClassNo(String classNo) {
56 this.classNo = classNo;
57 }
58
59 public String getClassName() {
60 return className;
61 }
62
63 public void setClassName(String className) {
64 this.className = className;
65 }
66
67
68
69 }
学生
View Code
1 import java.io.Serializable;
2 import javax.persistence.Column;
3 import javax.persistence.Entity;
4 import javax.persistence.Id;
5 import javax.persistence.JoinColumn;
6 import javax.persistence.ManyToOne;
7 import javax.persistence.Table;
8
9
10 @Entity
11 @Table(name="MyStudent")
12 public class Student implements Serializable {
13
14 /**
15 *
16 */
17 private static final long serialVersionUID = 4575350354658352861L;
18
19 @Id
20 @Column(name="stu_no",nullable=false)
21 private String stuNo;
22 @Column(name="stu_name",nullable=false)
23 private String stuName;
24
25 @Column(name="stu_age")
26 private Integer stuAge;
27
28 @Column(name="stu_address")
29 private String stuAddress;
30
31 /**
32 * 学生对应的班级
33 * JoinColumn中的name表示外键中的外键字段,
34 * 之前配置了referencedColumnName 属性,结果出现了 错误
35 */
36 @ManyToOne(targetEntity=MyClass.class)
37 @JoinColumn(name="stu_class_no",nullable= false)
38 private MyClass myClass;
39
40 public MyClass getMyClass() {
41 return myClass;
42 }
43 public void setMyClass(MyClass myClass) {
44 this.myClass = myClass;
45 }
46
47
48 public String getStuNo() {
49 return stuNo;
50 }
51 public void setStuNo(String stuNo) {
52 this.stuNo = stuNo;
53 }
54 public String getStuName() {
55 return stuName;
56 }
57 public void setStuName(String stuName) {
58 this.stuName = stuName;
59 }
60 public Integer getStuAge() {
61 return stuAge;
62 }
63 public void setStuAge(Integer stuAge) {
64 this.stuAge = stuAge;
65 }
66 public String getStuAddress() {
67 return stuAddress;
68 }
69 public void setStuAddress(String stuAddress) {
70 this.stuAddress = stuAddress;
71 }
72
73
74
75 }
然后是一个DAO公共类
View Code
1 import java.io.Serializable;
2 import java.lang.reflect.ParameterizedType;
3 import java.util.List;
4 import javax.persistence.EntityManager;
5 import javax.persistence.EntityManagerFactory;
6 import javax.persistence.EntityTransaction;
7 import javax.persistence.Persistence;
8 import javax.persistence.Query;
9
10 public class JpaCommonDao<T> {
11 private Class<T> clazz = null;
12
13 protected JpaCommonDao(Class<T> clazz){
14 this.clazz = clazz;
15 }
16
17 public JpaCommonDao(){
18 ParameterizedType type = (ParameterizedType)this.getClass().getGenericSuperclass();
19 clazz = (Class<T>)(type.getActualTypeArguments()[0]);
20 }
21
22 protected EntityManager getEm()
23 {
24 EntityManagerFactory factory = Persistence.createEntityManagerFactory("ntc-mssql");
25 EntityManager em = factory.createEntityManager();
26 return em;
27 }
28
29 protected void add(T item)
30 {
31 EntityManager em = this.getEm();
32 EntityTransaction tran= em.getTransaction();
33 tran.begin();
34 try
35 {
36 em.persist(item);
37 tran.commit();
38 }
39 catch (Exception e) {
40 e.printStackTrace();
41 tran.rollback();
42 }
43 em.close();
44
45
46 }
47
48
49 protected void update(T item)
50 {
51 EntityManager em = this.getEm();
52 EntityTransaction tran= em.getTransaction();
53 tran.begin();
54 try
55 {
56 em.refresh(item);
57 tran.commit();
58 }
59 catch (Exception e) {
60 e.printStackTrace();
61 tran.rollback();
62 }
63 em.close();
64 }
65
66
67 protected void delete(Serializable id) {
68 EntityManager em = this.getEm();
69 EntityTransaction tran= em.getTransaction();
70 tran.begin();
71 try
72 {
73 T item = em.find(clazz, id);
74 if(null == item)
75 return ;
76 em.remove(item);
77 tran.commit();
78 }
79 catch (Exception e) {
80 e.printStackTrace();
81 tran.rollback();
82 }
83 em.close();
84
85 }
86
87 protected T getObj(Serializable id) {
88 EntityManager em = this.getEm();
89 T item = null;
90 item = em.find(clazz, id);
91 em.close();
92 return item;
93 }
94
95
96 protected List<T> findList(String jpql)
97 {
98 EntityManager em = this.getEm();
99 Query query = em.createQuery(jpql);
100 List<T> list = query.getResultList();
101 em.close();
102 return list;
103 }
104 }
数据访问类
View Code
1 import java.util.List;
2 import com.demo.entity.MyClass;
3
4
5 public class MyClassDao extends JpaCommonDao<MyClass> {
6
7 public void add(MyClass cla )
8 {
9 super.add(cla);
10 }
11
12 public void update(MyClass cla){
13 super.update(cla);
14 }
15
16 public void delete(String id){
17 super.delete(id);
18 }
19
20 public MyClass getClass(String id){
21 return super.getObj(id);
22 }
23
24
25 /**
26 * 根据主键获取班级信息
27 * @param id 主键ClassNo
28 * @return
29 */
30 public MyClass queryClass(String id) {
31 String jpql="SELECT c FROM MyClass c left join fetch c.student WHERE c.classNo = "+id;
32 List<MyClass> list = super.findList(jpql);
33 if(list.size()>0){
34 return list.get(0);
35 }
36 return null;
37
38 }
39
40 /**
41 * 获取批量班级信息
42 * @return
43 */
44 public List<MyClass> queryList()
45 {
46 String jpql="SELECT c FROM MyClass c left join fetch c.student ";
47
48 List<MyClass> list = super.findList(jpql);
49
50 if(list.size()>0){
51 return list;
52 }
53 return null;
54 }
55
56
57 }
View Code
1 import java.util.List;
2
3 import com.demo.entity.Student;
4
5 public class StudentDao extends JpaCommonDao<Student> {
6
7 public void add(Student stu)
8 {
9 super.add(stu);
10 }
11
12 public void update(Student stu){
13 super.update(stu);
14 }
15
16 public void delete(String id){
17 super.delete(id);
18 }
19
20 public Student getStudent(String id)
21 {
22 return super.getObj(id);
23 }
24
25 public Student queryStuden(String id){
26 String jpql="SELECT s FROM Student s left join fetch s.myClass WHERE s.stuNo = "+id;
27 List<Student> list = super.findList(jpql);
28 if(list.size()>0){
29 return list.get(0);
30 }
31 return null;
32 }
33
34 public List<Student> getStudensByClassNo(String clsNo){
35 String jpql="SELECT s FROM Student s left join fetch s.myClass WHERE s.myClass.classNo = "+clsNo;
36 List<Student> list = super.findList(jpql);
37 if(list.size()>0){
38 return list;
39 }
40 return null;
41 }
42 }
最后的测试类
View Code
1 public class MyTest {
2
3
4 /**
5 * 根据班级编号获得班级信息
6 */
7 public void getMyClass()
8 {
9 MyClassDao dao =new MyClassDao();
10 MyClass cls = dao.getClass("0601");
11 System.out.println(cls.getClassName());
12 }
13
14 /**
15 * 添加一个班级
16 */
17 public void addClass()
18 {
19 MyClass cla = new MyClass();
20 cla.setClassName("06120班");
21 cla.setClassNo("0612");
22 cla.setStudent(null);//如果不设定为null的话,是会抛出错误的。因为我在实体类中new 了一次。如果不new一次的话,就不需要
23 new MyClassDao().add(cla);
24
25 }
26
27 /**
28 * 添加一个班级和相应学生通过添加班级对象
29 */
30 @Test
31 public void addClassAndStudentByClass()
32 {
33 MyClass cla = new MyClass();
34 cla.setClassName("0613班");
35 cla.setClassNo("0613");
36
37 Student stu1 =new Student();
38 stu1.setMyClass(cla);
39 stu1.setStuName("13肖文斌");
40 stu1.setStuNo("061301");
41
42 Student stu2 =new Student();
43 stu2.setMyClass(cla);
44 stu2.setStuName("1302");
45 stu2.setStuNo("061303");
46
47 Student stu3 =new Student();
48 stu3.setMyClass(cla);
49 stu3.setStuName("1305");
50 stu3.setStuNo("061305");
51
52 //因为在班级对象中,设置了维护对方关系的全部,所以在添加班级的一方的时候,可以将多方添加进去
53 Set<Student> stus =new HashSet<Student>();
54 stus.add(stu1);
55 stus.add(stu2);
56 stus.add(stu3);
57 cla.setStudent(stus);
58 new MyClassDao().add(cla);
59 }
60
61
62 /***
63 * 删除 一方 对象
64 * 因为 一方对象 设置了双方关系维护规则为 ALL,所以会将多方的数据同时删除
65 */
66 public void deleteStudenAndClassByCla()
67 {
68 new MyClassDao().delete("0613");
69 }
70
71 }
真个简单的Demo就完成了。
然后而外啰嗦几句,
C#是后起之秀,并且本身就是借鉴JAVA来进行研发的,后来C#中的许多思想也被JAVA使用,因此两门语言的相似度可以达到90%,语法这些几乎无差别,就是命名差别大了些。另外,两门语言的一些规范,其实也有潜规则。JAVA的多使用骆驼命名法,C#中多使用帕斯卡命名法。