Hibernate框架入门一:

Hibernate 概念:
(1.)Hibernate 是一个开放源代码的对象关系映射框架,它对 JDBC 进行了非常轻量级的对象封装,它将 pojo 与数据库表建立映射关系,是一个全自动的 ORM(Object - Relationship - Mapping)框架,Hibernate 可以自动生成 SQL 语句,自动执行,使得 Java 程序员可以随心所欲的使用对象编程思维来操纵数据库。
(2.)Hibernate 可以应用在任何使用 JDBC 的场合。
(3.)Gavin King 他是 Hibernate 的创始人,也是那本经典的 Hibernate in action 的作者。
Hibernate 原本是 JBOSS 旗下的产品,2006 年 JBOSS 被 RED HAT 收购,变成了红帽公司的产品。

今天我们拿个简单的案例来向大家简单的介绍一下Hibernate框架
案例:
首先我们在eclipse上创建一个maven项目,首先我们要配置pom.xml
如果你们要用到我这里的代码的话别一次性就copy进自己的项目中去 要一条一条的来 俗话说心急吃不了热豆腐嘛
pom.xml:

<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.lihao</groupId>
  <artifactId>qqqq</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>qqqq 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>qqqq</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>

当然要记得配置web.xml这里我就不配置了你们可以点击我下面给你们的链接去看我以前配置的 这里的web.xml配置跟那里的一样点这里可以看到这次所需web.xml的配置

配置完wbe.xml之后你就可以接下来的创建hibernate.cfg.xml:
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">root</property>
		<property name="connection.password">123</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/122?useUnicode=true&amp;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/lihao/one/entity/User.hbm.xml" />
		
	</session-factory>
</hibernate-configuration>

创建完 hibernate.cfg.xml 之后就根据你所要操作的表写一个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:数据库对应的列段
 			insert="false" update="false" 
 			上面的表示的含义是:该列段或者说该属性制作查询用,不做更新
 	 -->
	<class name="com.lihao.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.lang.String" column="birthday">
		</property>
		<property insert="false" update="false" name="createDatetime"
			type="java.lang.String" column="create_datetime">
		</property>
		<property name="remark" type="java.lang.String" column="remark">
		</property>
	</class>
 </hibernate-mapping>

然后创建一个我们要用到的实体类:
User.java:

package com.lihao.one.entity;

import java.sql.Date;
import java.sql.Timestamp;

public class User {
	private Integer id;
	private String userName;
	private String userPwd;
	private String sex;
	private String birthday;
	private String realName;
	private String createDatetime;
	private String remark;
	
	
	public String getBirthday() {
		return birthday;
	}
	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}
	public String getCreateDatetime() {
		return createDatetime;
	}
	public void setCreateDatetime(String createDatetime) {
		this.createDatetime = createDatetime;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPwd() {
		return userPwd;
	}
	public void setUserPwd(String userPwd) {
		this.userPwd = userPwd;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getRealName() {
		return realName;
	}
	public void setRealName(String realName) {
		this.realName = realName;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	
	public User() {
		super();
	}
	public User(Integer id, String userName, String userPwd, String sex, String birthday, String realName,
			String createDatetime, String remark) {
		super();
		this.id = id;
		this.userName = userName;
		this.userPwd = userPwd;
		this.sex = sex;
		this.birthday = birthday;
		this.realName = realName;
		this.createDatetime = createDatetime;
		this.remark = remark;
	}
	
	
	public User(String userName, String userPwd, String sex, String birthday, String realName, String createDatetime,
			String remark) {
		super();
		this.userName = userName;
		this.userPwd = userPwd;
		this.sex = sex;
		this.birthday = birthday;
		this.realName = realName;
		this.createDatetime = createDatetime;
		this.remark = remark;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", userPwd=" + userPwd + ", sex=" + sex + ", birthday="
				+ birthday + ", realName=" + realName + ", createDatetime=" + createDatetime + ", remark=" + remark
				+ "]";
	}
	
}

然后就开始写增删查改的代码:
首先是增加的:

package com.lihao.one.demo;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;

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

import com.lihao.one.entity.User;

/**
 * hibernate新增演示
 * @author 李浩
 *
 */
public class InsertDemo {
	public static void main(String[] args) {
		Configuration configure = new Configuration().configure("/hibernate.cfg.xml");
		SessionFactory sessionFactory = configure.buildSessionFactory();
		//会话、而这里的会话指的是操作数据库的链接
		Session session = sessionFactory.openSession();
		
		Transaction transaction = session.beginTransaction();
		session.save(new User("dd", "123", "男", "2001-12-2", "沙漠骆驼", null, "九个脑袋"));
		
		transaction.commit();
		
		session.close();
	}
}

然后是查看的:

package com.lihao.one.demo;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * hibernate查询演示
 * @author 李浩
 *
 */
public class QueryDemo {
	public static void main(String[] args) {
		Configuration configure = new Configuration().configure("/hibernate.cfg.xml");
		SessionFactory sessionFactory = configure.buildSessionFactory();
		//会话、而这里的会话指的是操作数据库的链接
		Session session = sessionFactory.openSession();
		List list = session.createQuery("from User").list();
		for(Object obj : list) {
			System.out.println(obj);
		}
		session.close();
	}
}

修改的:

package com.lihao.one.demo;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;

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

import com.lihao.one.entity.User;

/**
 * hibernate新增演示
 * @author 李浩
 *
 */
public class UpdateDemo {
	public static void main(String[] args) {
		Configuration configure = new Configuration().configure("/hibernate.cfg.xml");
		SessionFactory sessionFactory = configure.buildSessionFactory();
		//会话、而这里的会话指的是操作数据库的链接
		Session session = sessionFactory.openSession();
		
		Transaction transaction = session.beginTransaction();
//		session.save(new User(null, "ss", "123", "男", new Date(System.currentTimeMillis()), "李毅", new Timestamp(System.currentTimeMillis()), "九个脑袋"));
//		User u = new User(null, "ss", "123", "男", new Date(System.currentTimeMillis()), "李毅", new Timestamp(System.currentTimeMillis()), "九个脑袋");
//		u.setRealName("小王八蛋2");
		User user = session.get(User.class, 2);
		user.setRealName("小王八蛋");
		
		System.out.println(user);
		transaction.commit();
		
		session.close();
	}
}

最后是删除的:

package com.lihao.one.demo;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;

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

import com.lihao.one.entity.User;

/**
 * hibernate新增演示
 * @author 李浩
 *
 */
public class DeleteDemo {
	public static void main(String[] args) {
		Configuration configure = new Configuration().configure("/hibernate.cfg.xml");
		SessionFactory sessionFactory = configure.buildSessionFactory();
		//会话、而这里的会话指的是操作数据库的链接
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		
		User user = new User();
		user.setId(1);;
		session.delete(user);
		
		transaction.commit();
		session.close();
	}
}

这次的Hibernate框架就搞完了

总结:
hibernate.cfg.xml(1)/*.hbm.xml(N)
实体映射文件一定要加到核心配置文件

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐