本例以Windows, JDK1.8, MySQL5 为基础,演示使用Hibernate5来完成增删查改的操作。

使用的工具及技术

1.Hibernate 5.2.10.Final
2.MySQL 5
3.Eclipse
4.Maven 3

项目结构

Maven配置

使用Maven构建项目,当然应该先添加相关的jar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!– hibernate core –>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>

<!– mysql connection –>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.28</version>
</dependency>

项目代码code

Model

本来主要是对单一对象模型就行数据库的操作,以Student对象为例:

Student.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package com.devnp.hibernate.core.model;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;


@Entity
@Table(name = "Student")
public class Student implements Serializable{

/**
* @author duliu
*/
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "ID")
private Long id ;

@Column(name = "NAME")
private String name ;

@Column(name = "AGE", nullable= false)
private Integer age ;

@Column(name = "BIRTH_DATE")
@Temporal(TemporalType.DATE)
private Date birthDate ;

public Student() {
super();
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public Date getBirthDate() {
return birthDate;
}

public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}

@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age
+ ", birthDate=" + birthDate + "]";
}


}

增删查改

保存对象包数据库 SaveStudent.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.devnp.hibernate.core.quickstart;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.devnp.hibernate.core.model.Student;
import com.devnp.hibernate.core.util.HibernateProUtil;
import com.devnp.hibernate.core.util.HibernateXmlUtil;

public class SaveStudent {

/**
* 演示保存对象到DB
* @param args
*/
public static void main(String[] args) {

//SessionFactory sessionFactory = HibernateXmlUtil.getSessionFactory();

SessionFactory sessionFactory = HibernateProUtil.getSessionFactory();

Session session = sessionFactory.openSession();

Student student = new Student() ;

student.setName("Jack Chen");
student.setAge(30);
student.setBirthDate(new Date());

session.save(student);

session.close();

HibernateProUtil.shutdown();
}


}

查询保存的数据库 SelectSudent.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.devnp.hibernate.core.quickstart;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.devnp.hibernate.core.model.Student;
import com.devnp.hibernate.core.util.HibernateXmlUtil;

public class SelectSudent {

/**
* 从DB里面查询出数据
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

SessionFactory sessionFactory = HibernateXmlUtil.getSessionFactory() ;

Session session = sessionFactory.openSession() ;

List<Student> list = session.createQuery("from Student").list() ;

session.close();

HibernateXmlUtil.shutdown();

for (Student student : list) {
System.out.println(student);
}
}

}

修改数据 UpdateStudent.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.devnp.hibernate.core.quickstart;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.devnp.hibernate.core.model.Student;
import com.devnp.hibernate.core.util.HibernateXmlUtil;

public class UpdateStudent {

/**
* 查询出表的数据并更新
* @param args
*/
public static void main(String[] args) {

//updateWithObj();
updateWithHQL();
}

/**
* 同对象来执行更新
*/
public static void updateWithObj(){
SessionFactory sessionFactory = HibernateXmlUtil.getSessionFactory() ;

Session session = sessionFactory.openSession() ;

Transaction tx = session.beginTransaction(); //开启一个事物

String hql = "from Student where id=:id" ;

Student student = (Student) session.createQuery(hql).setParameter("id", 1L).uniqueResult() ;

System.out.println(student);

student.setName("Jack Li");

session.update(student);

tx.commit(); //提交一个事物

session.close();

HibernateXmlUtil.shutdown();
}

/**
* 通过HQL来支持更新
*/
public static void updateWithHQL(){
SessionFactory sessionFactory = HibernateXmlUtil.getSessionFactory() ;

Session session = sessionFactory.openSession() ;

Transaction tx = session.beginTransaction();

String hql = "update Student set name=:name where id=:id";

session.createQuery(hql).setParameter("name", "Jack Wang").setParameter("id", 1L).executeUpdate() ;

tx.commit();

session.close();

HibernateXmlUtil.shutdown();
}
}

删除数据 DeleteStudent.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.devnp.hibernate.core.quickstart;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.devnp.hibernate.core.model.Student;
import com.devnp.hibernate.core.util.HibernateXmlUtil;

public class DeleteStudent {

public static void main(String[] args) {
// TODO Auto-generated method stub

deleteWithObj();
//deleteWithHQL();
}

/**
* 通过对象来删除
*/
public static void deleteWithObj(){
SessionFactory sessionFactory = HibernateXmlUtil.getSessionFactory() ;

Session session = sessionFactory.openSession() ;

Transaction tx = session.beginTransaction(); //开启一个事物

String hql = "from Student where id=:id" ;

Student student = (Student) session.createQuery(hql).setParameter("id", 3L).uniqueResult() ;

System.out.println(student);

session.delete(student);

tx.commit(); //提交一个事物

session.close();

HibernateXmlUtil.shutdown();
}

/**
* 通过执行HQL来删除数据
*/
public static void deleteWithHQL(){
SessionFactory sessionFactory = HibernateXmlUtil.getSessionFactory() ;

Session session = sessionFactory.openSession() ;

Transaction tx = session.beginTransaction();

String hql = "delete from Student where id=:id";

session.createQuery(hql).setParameter("id", 1L).executeUpdate();

tx.commit();

session.close();

HibernateXmlUtil.shutdown();
}

}

[/code]

相关

关于SessionFactory的创建可以参考:Hibernate5 SessionFactory 的获取

代码下载