什么是Hibernate

ORM框架/持久层框架jdbc的一个框架
object reference mapping
通过管理对象来改变数据库中的数据
通过管理对象来操作数据库

优势:跨数据库的无缝移植

Hibernate简易增删改查

导入pom依赖

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

创建核心配置文件hibernate.cfg.xml
此处需要导DTD约束(依次寻找)
Hibernate入门-LMLPHP
Hibernate入门-LMLPHP
将这串代码放入hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

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/mysql?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/tzx/one/entity/User.hbm.xml" />
		<!-- 主键生成策略 -->

	</session-factory>

</hibernate-configuration>

创建实体类User

package com.tzx.one.entity;

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

public class User {
	private Integer id;
	private String userName;
	private String userPwd;
	private String realName;
	private String sex;
	private Date birthday;
	private Timestamp createDatetime;
	private String remark;
	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 getRealName() {
		return realName;
	}
	public void setRealName(String realName) {
		this.realName = realName;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public Timestamp getCreateDatetime() {
		return createDatetime;
	}
	public void setCreateDatetime(Timestamp createDatetime) {
		this.createDatetime = createDatetime;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	public User(Integer id, String userName, String userPwd, String realName, String sex, Date birthday,
			Timestamp createDatetime, String remark) {
		super();
		this.id = id;
		this.userName = userName;
		this.userPwd = userPwd;
		this.realName = realName;
		this.sex = sex;
		this.birthday = birthday;
		this.createDatetime = createDatetime;
		this.remark = remark;
	}
	public User() {
		super();
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", userPwd=" + userPwd + ", realName=" + realName
				+ ", sex=" + sex + ", birthday=" + birthday + ", createDatetime=" + createDatetime + ", remark="
				+ remark + "]";
	}



}

写一个实体映射文件User.hbm.xml(注意与实体类同包,并且一个实体类有一个实体映射文件)
此处也需要导入DTD约束

<?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:属性对应该=的表中的那个列段
 -->
	<class name="com.tzx.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>

实现增删改查
查询

package com.tzx.one.test;

import java.util.List;

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

/**
 * hiberbate中的查询案例
 * @author
 *
 */
public class QueryDemo {
	public static void main(String[] args) {
//		对hiberbate.cfg.xml进行建模拿到session-factory工厂(两步)
		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);
		}
//		关闭资源
		session.close();
	}

}

效果
Hibernate入门-LMLPHP
增加

package com.tzx.one.test;

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.tzx.one.entity.User;

/**
 * hibernat 中的增加
 * @author
 *
 */
public class AddDemo {

public static void main(String[] args) {
	//对hibernat.cfg.xml进行建模拿到sessionfactory工厂 (两步) 1.建模  2.拿到工厂
	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("tanzhixian", "123", "大贤哥", "男",new Date(System.currentTimeMillis()), new Timestamp(System.currentTimeMillis()),"暂无"));
    //提交事务
    transaction.commit();
	//关闭资源
    session.close();
}
}


Hibernate入门-LMLPHP
修改

package com.tzx.one.test;

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.tzx.one.entity.User;

/**
 * hibernat 中的修改
 * @author
 *
 */
public class EditDemo {

public static void main(String[] args) {
	//对hibernat.cfg.xml进行建模拿到sessionfactory工厂 (两步) 1.建模  2.拿到工厂
	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("tanzhixian", "123", "大贤", "男",new Date(System.currentTimeMillis()), new Timestamp(System.currentTimeMillis()),"暂无");
//    user.setId(15);
//    session.update(user);

    //第二种

    User user = session.get(User.class, 15);
    System.out.println(user);
    user.setRealName("大贤2");

    //提交事务
    transaction.commit();
	//关闭资源
    session.close();
}
}


Hibernate入门-LMLPHP
删除

package com.tzx.one.test;

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.tzx.one.entity.User;

/**
 * hibernat 中的删除
 * @author
 *
 */
public class DelDemo {

public static void main(String[] args) {
	//对hibernat.cfg.xml进行建模拿到sessionfactory工厂 (两步) 1.建模  2.拿到工厂
	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();
}
}


Hibernate入门-LMLPHP

如何看jar包有没有冲突,右键
Hibernate入门-LMLPHP

如果出现BUILD SUCCESS代表成功Hibernate入门-LMLPHP

08-06 06:29