hibernate入门
1. 什么是hibernate
ORM框架/持久层框架 jdbc的一个框架
object reference mapping
通过管理对象来改变数据库中的数据
通过管理对象来操作数据库
mybatis
2. 如何在项目中添加hibernate支持(手动添加)
2.1 添加hibernate相关依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.huang</groupId> <artifactId>T226_hibernate</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>T226_hibernate Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <junit.version>4.12</junit.version> <servlet.version>4.0.0</servlet.version> <hibernate.version>5.3.0.Final</hibernate.version> <mysql.driver.version>5.1.46</mysql.driver.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.driver.version}</version> </dependency> </dependencies> <build> <finalName>T226_hibernate</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> </plugins> </build> </project>
2.2 在resource目录下添加hibernate.cfg.xml(核心配置文件)
2.2.1 添加DTD支持
我们从/org/hibernate/hibernate-configuration-3.0.dtd里面考过来就行了
2.2.2 添加Hibernate的配置
2.2.2.1 数据库相关(connection.username|connection.password|connection.url|connection.driver_class|dialect)
2.2.2.2 调试相关(show_sql|format_sql)
hibernate.cfg.xml
<?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> <!-- 1. 数据库相关 --> <property name="connection.username">huang</property> <property name="connection.password">root</property> <property name="connection.url">jdbc:mysql://localhost:3306/huang?useUnicode=true&characterEncoding=UTF-8 </property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 配置本地事务(No CurrentSessionContext configured!) --> <property name="hibernate.current_session_context_class">thread</property> <!-- 2. 调试相关 --> <property name="show_sql">true</property> <property name="format_sql">true</property> <!-- 3. 添加实体映射文件 --> <mapping resource="com/huang/one/entity/User.hbm.xml" /> </session-factory> </hibernate-configuration>
实体映射文件一定要加到核心配置文件
2.3 在开发阶段再创建实体类和实体映射文件(*.hbm.xml)
User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <!-- class标签中: name:实体类的全路径 table:实体类对应数据库中的表 id标签: name:实体类中的属性(映射的是表的主键) type:属性对应的类型 column:属性对应的表中的哪一个列段 property: name:实体类中的属性(映射的是表 的非主键) type:属性对应的类型 column:属性对应的表中的哪一个列段 List list=session.creteQuery("from User").list(); 1、建模hibernate.cfg.xml对象,从中拿到了com/huang/one/entity/User.hbm.xml 2、建模了User.hbm.xml,拿到了com.huang.one.entity.User/t_hibernate_user 3、User user=Class.forName("com.huang.one.entity.User").newInstance(); Fild userNameField= user.getClass("userName"); Fild userPwdField= user.getClass("userPwd"); select user_name,user_pwd,real_name,...from t_hibernate_user 最后user中的所有属性值都有了 4、循环上一步操作,最终所有user实例都放入了list集合中就是List list --> <class name="com.huang.one.entity.User" table="t_hibernate_user"> <id name="id" type="java.lang.Integer" column="id"> <generator class="increment" /> </id> <property name="userName" type="java.lang.String" column="user_name"> </property> <property name="userPwd" type="java.lang.String" column="user_pwd"> </property> <property name="realName" type="java.lang.String" column="real_name"> </property> <property name="sex" type="java.lang.String" column="sex"> </property> <property name="birthday" type="java.sql.Date" column="birthday"> </property> <property insert="false" update="false" name="createDatetime" type="java.sql.Timestamp" column="create_datetime"> </property> <property name="remark" type="java.lang.String" column="remark"> </property> </class> </hibernate-mapping>
3、hibernate的增删改查
3.1新增
package com.huang.one.test;
import java.sql.Date;
import java.sql.Timestamp;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.huang.one.entity.User;
/**
* hibernate 中增加案例
* @author AdministratorT
*
*/
public class AddDemo {
public static void main(String[] args) {
// 对hibernate.cfg.xml进行建模拿到sessionfactory工厂(两步)
Configuration configure= new Configuration().configure("/hibernate.cfg.xml");
SessionFactory sessionFactory= configure.buildSessionFactory();
// 通过工厂获取到session会话(用来操作数据库)
Session session = sessionFactory.openSession();
// 获取事务对象
Transaction transaction=session.beginTransaction();
// 直接操作数据库
session.save(new User("wangcai", "565757", "旺财", "公", new Date(System.currentTimeMillis()), new Timestamp(System.currentTimeMillis()), "暂无"));
// 提交事务
transaction.commit();
// 关闭资源
session.close();
}
}
3.2修改
package com.huang.one.test; import java.sql.Date; import java.sql.Timestamp; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.huang.one.entity.User; /** * hibernate 中修改案例 * @author AdministratorT * */ public class EditDemo { public static void main(String[] args) { // 对hibernate.cfg.xml进行建模拿到sessionfactory工厂(两步) Configuration configure= new Configuration().configure("/hibernate.cfg.xml"); SessionFactory sessionFactory= configure.buildSessionFactory(); // 通过工厂获取到session会话(用来操作数据库) Session session = sessionFactory.openSession(); // 获取事务对象 Transaction transaction=session.beginTransaction(); // 直接操作数据库 User user=new User("wangcai", "123456", "旺财2", "男", new Date(System.currentTimeMillis()), new Timestamp(System.currentTimeMillis()), "暂无"); user.setId(15); session.update(user); // 修改单个 // User user=session.get(User.class, 15); // user.setRealName("旺财2"); // 提交事务 transaction.commit(); // 关闭资源 session.close(); } }
3.3查询
package com.huang.one.test; import java.sql.Timestamp; import java.util.List; import javax.transaction.Transaction; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import java.io.Serializable; import java.sql.Date; import com.huang.one.entity.User; /** * hibernate 中查询案例 * @author Administrator * */ public class QueryDemo { public static void main(String[] args) { // 对hibernate.cfg.xml进行建模拿到sessionfactory工厂(两步) Configuration configure= new Configuration().configure("/hibernate.cfg.xml"); SessionFactory sessionFactory= configure.buildSessionFactory(); // 通过工厂获取到session会话(用来操作数据库) Session session = sessionFactory.openSession(); // 直接操作数据库 // 查询所有 List list = session.createQuery("from User").list(); for (Object obj : list) { System.out.println(obj); } // 查询单个 // User user=session.get(User.class, 15); // System.out.println(user); // 关闭资源 session.close(); } }
3.4删除
package com.huang.one.test; import java.sql.Date; import java.sql.Timestamp; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.huang.one.entity.User; /** * hibernate 中删除案例 * @author AdministratorT * */ public class DelDemo { public static void main(String[] args) { // 对hibernate.cfg.xml进行建模拿到sessionfactory工厂(两步) Configuration configure= new Configuration().configure("/hibernate.cfg.xml"); SessionFactory sessionFactory= configure.buildSessionFactory(); // 通过工厂获取到session会话(用来操作数据库) Session session = sessionFactory.openSession(); // 获取事务对象 Transaction transaction=session.beginTransaction(); // 直接操作数据库 User user=new User(); user.setId(15); session.delete(user); // 提交事务 transaction.commit(); // 关闭资源 session.close(); } }