Hibernate5.2.4Final学习(二)注解

采用注解(Annotation)的方式,建立类与数据库表单的关系,这时不需要写
与该类对应的hbm.xml文件。

新建一个Teacher类

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.nick.testhibernate;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Teacher {
private int id;
private String name;
private String title;
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}

然后再src下的hibernate.cfg.xml文件中新增一句,具体如下

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
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<!-- JDBC connection pool (use the built-in) -->
<!-- <property name="connection.pool_size">1</property> -->
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<!--<property name="current_session_context_class">thread</property>-->
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<!--<property name="hbm2ddl.auto">update</property>-->
<mapping resource="com/nick/testhibernate/Student.hbm.xml"/>
<!-- add new -->
<mapping class="com.nick.testhibernate.Teacher"/>
</session-factory>
</hibernate-configuration>

最后建一个TeacherTest类

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
package com.nick.testhibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class TeacherTest {
public static void main(String[] args) {
Teacher t = new Teacher();
t.setTitle("Doctor");
t.setId(1);
t.setName("wang");
Configuration cfg = new Configuration(); // 不用AnnotationConfiguration
SessionFactory sf = cfg.configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(t);
session.getTransaction().commit();
session.close();
sf.close();
}
}

测试前,需要再数据库中新建一个表,名为teacher,并添加相应的字段

您的支持将是我前进的不懈动力