这篇文章是学习ORM的第一步!
老师讲了,学习ORM要分三步:
1、Why ORM?
2、What ORM?
3、How ORM?
这三步前两步的表面意思很好理解,但是深入理解以及第三步的具体内容还需要放到以后的学习中去。
下面步入正题:
1、首先下载所需要的Hibernate文件,这里用的是老师提供的hibernate-release-5.2.10.Final.
2、导入所需要的jar包,因为老师比较大方,所以我们也得到了Hibernate配置的全部jar包,下面是我的截图:
3、创建实体类User.java:
代码如下:
package com;
public class User {
private int id;
private String name;
private String password;
private int age;
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
4、配置映射关系(实体类和数据库表的对应关系):
代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.User" table="zxw">
<id name="id" column="ID" type="int">
<generator class="increment"/>
</id>
<property name="name" column="name" type="java.lang.String" />
<property name="password" column="password" type="java.lang.String" />
<property name="age" column="age" type="int"/>
</class>
</hibernate-mapping>
5、创建配置文件:
代码如下:
<!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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/zxw</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
6、编写测试类:
代码如下:
package test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.User;
public class TestUser {
public static void main(String[] args) {
Configuration conf = new Configuration().configure();//1、读取配置文件
SessionFactory sf = conf.buildSessionFactory();// 2、创建SessionFactory
Session session = sf.openSession();// 3、打开Session
Transaction tx = null;
try{
tx = session.beginTransaction();// 4、开始一个事务
// 5、持久化操作
User user = new User();
user.setName("zxw");
user.setPassword("1514010628");
user.setAge(22);
session.save(user);
tx.commit();// 6、 提交事务
}catch(Exception e){
if (null!=tx){tx.rollback();}
e.printStackTrace();
}finally{
session.close();// 7、关闭Session
}
}
}
7、运行测试类:
8、刷新数据库,导入信息已存在:
9、Hibernate配置与测试完成!