Hibernate的xml方法配置和操作代码

一、gradle中包:

    compile group: 'org.hibernate', name: 'hibernate-core', version: '5.2.12.Final'
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.40'

二、项目中导入hibernate
  1、向gradle配置文件中引入一中的两个包
  2、点击Hibernate的xml方法配置和操作代码按钮,在facets中添加hibernate,
Hibernate的xml方法配置和操作代码

这时,右下角会出现一个Hibernate的xml方法配置和操作代码持久化选项卡,点击该选项卡:Hibernate的xml方法配置和操作代码右键点击B7_main选项,Hibernate的xml方法配置和操作代码

点击Generate Persisitence Mapping,点击By Database Schema,

Hibernate的xml方法配置和操作代码

(需要自己新建一个po层),选择自己需要的数据库,表以及关系,然后ok即可

它会自动生成一个hibernate.cfg.xml的配置文件,将其拖入resources目录下即可

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url"><![CDATA[jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8]]></property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username"></property>
<property name="connection.password"></property>
<mapping resource="User.hbm.xml"/>
<!-- DB schema will be updated if needed -->
<!-- <property name="hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>

其中mapping标签必须放在property标签下,不能混着放,每次更新gradle后记得要重新配置数据库的链接密码。

还会自动关系映射出一个和user表对应的类:User(存放于po层)

package com.weikun.po;

/**
* Created by Administrator on 2018/3/25.
*/
public class User {
private int id;
private String username;
private String password; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; User user = (User) o; if (id != user.id) return false;
if (username != null ? !username.equals(user.username) : user.username != null) return false;
if (password != null ? !password.equals(user.password) : user.password != null) return false; return true;
} @Override
public int hashCode() {
int result = id;
result = 31 * result + (username != null ? username.hashCode() : 0);
result = 31 * result + (password != null ? password.hashCode() : 0);
return result;
}
}

之后就可以在dao层通过控制User类下的属性方法来映射操控底层数据库的数据了。

还会自动生成和映射到user表的配置文件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="com.weikun.po.User" table="user" schema="test">
<id name="id">
<column name="id" sql-type="int(11)"/>
</id>
<property name="username">
<column name="username" sql-type="varchar(200)" length="200"/>
</property>
<property name="password">
<column name="password" sql-type="varchar(20)" length="20"/>
</property>
</class>
</hibernate-mapping>

其中<id>标签是指主键,如果用注解的话是@id来标注主键。

联合主键的配置文件代码如下:

<composite-id>
<key-property name="username">
<column name="username" sql-type="varchar(10)" length="10"/>
</key-property>
<key-property name="sex">
<column name="sex" sql-type="varchar(10)" length="10"/>
</key-property>
</composite-id>

三、dao层的操作代码

package com.weikun.dao;

import com.weikun.po.User;
import com.weikun.po.User5;
import com.weikun.po.User5PK;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test; import java.util.List; /**
* Created by Administrator on 2018/3/25.
*/
public class UserDAOImpl {
private Configuration configuration=null;
private SessionFactory sessionFactory=null; public UserDAOImpl(){
configuration=new Configuration().configure("hibernate.cfg.xml");//1、将配置文件加载到配置类的对象中 sessionFactory=configuration.buildSessionFactory();//2、使用配置对象创建对话工厂 }
@Test
public void queryByAll(){ Session session=null;
session=sessionFactory.openSession();//3、使用对话工厂打开会话
List<User> list=session.createQuery("from User ").list();//sql--H QL4、执行回话的具体行为
list.forEach(user->System.out.printf("%s-%s\n",user.getUsername(),user.getPassword())); session.close();//5、关闭会话
} @Test
public void queryById(){
Session session=null;
session=sessionFactory.openSession();
User user=session.get(User.class,288);//get
System.out.printf("%s-%s",user.getUsername(),user.getPassword());
session.close(); }
@Test
public void update(){
Session session=null;
session=sessionFactory.openSession();
Transaction transaction=session.beginTransaction();
User user=new User();
user.setId(285);
user.setUsername("MENG");
user.setPassword("8888");
try{
session.update(user);
transaction.commit();
}catch(Exception e){
transaction.rollback();
e.printStackTrace();
}
session.close(); }
@Test
public void del(){
Session session=null;
session=sessionFactory.openSession();
Transaction transaction=session.beginTransaction();
User user=new User();
user.setId(286);
try{
session.delete(user);
transaction.commit();
}catch(Exception e){
transaction.rollback();
e.printStackTrace();
}
session.close();
}
@Test
public void add5(){
Session session=null;
session=sessionFactory.openSession();
Transaction transaction=session.beginTransaction();
User5 user5=new User5();
user5.setUsername("rose1");
user5.setSex("f");
user5.setAge(199);
try{
session.save(user5);
transaction.commit();
}catch(Exception e){
transaction.rollback();
e.printStackTrace();
} session.close();
}
@Test
public void add(){
Session session=null;
session=sessionFactory.openSession();
Transaction transaction=session.beginTransaction();
User user=new User();
user.setPassword("yu");
user.setUsername("YUYUYU");
try{
session.save(user); transaction.commit();
}catch(Exception e){
transaction.rollback();
e.printStackTrace();
} session.close(); }
}

先创建一个配置文件Configuration

 private Configuration configuration=null;

再创建一个SessionFactory工厂

private SessionFactory sessionFactory=null;
public UserDAOImpl(){
configuration=new Configuration().configure("hibernate.cfg.xml");//1、将配置文件加载到配置类的对象中 sessionFactory=configuration.buildSessionFactory();//2、使用配置对象创建对话工厂 }

在构造器中实例化配置对象,创建对话工厂。

使用sessionFactory开一个回话session

除了查询以外,其他的增删改都需要使用事务管理,使用session开始一个事务

session=sessionFactory.openSession();
Transaction transaction=session.beginTransaction();

需要做一个trycatch,try中处理事务,catch中进行事务回滚,最后关闭事务

 try{
session.save(user); transaction.commit();
}catch(Exception e){
transaction.rollback();
e.printStackTrace();
} session.close();
 
 
上一篇:【JAVA学习】struts2的action中使用session的方法


下一篇:Java中的文件和stream流的操作代码