第二章:Hibernate+注解+Maven,集成mysql

Hibernate+注解环境搭建

一)创建一个maven project,项目名称叫oyj-hibernate,项目结构图如下:

 

第二步:在项目中pom.xml文件中引入Hibernate的Jar

配置如下:

<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.oyj.hibernate</groupId>
    <artifactId>oyj_hibernate</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  
    <dependencies>
        <!-- hibernate jar -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.10.Final</version>
        </dependency>
	
        <!-- oracle jdbc jar-->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.1.0.6.0</version>
        </dependency>
    </dependencies>
</project>

 

第三步:在数据库创建一个表

脚本如下:

create table employee(
    userid number,
    username varchar2(50),
    sex number
);

select count(0) from employee;

select * from employee;

delete from employee;
commit;

 

第四步:在src/main/java创建一个实体类,类名为EmployeeEntity

代码如下:

package com.oyj.hibernate.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "employee")
public class EmployeeEntity implements Serializable {
	
    private static final long serialVersionUID = 1L;
	
    @Id
    @Column(name="userid")
    private Integer userID;
	
    @Column(name="username")
    private String userName;
	
    @Column(name="sex")
    private Integer sex;

    public Integer getUserID() {return userID;}
    public void setUserID(Integer userID) {this.userID = userID;}

    public String getUserName() {return userName;}
    public void setUserName(String userName) {this.userName = userName;}

    public Integer getSex() {return sex;}
    public void setSex(Integer sex) {this.sex = sex;}
}

 

实体类注解说明

@Entity

标志着这个类为一个实体bean

 

@Table

标识数据库表的详细信息,例如表名,索引等

 

@Id

一个实体bean都会有一个主键,在类中可以用@Id来进行注释,在新增数据时,会有默认的主键生成规则,也可以自己指定

 

@Column

注释用于指定某一列与某一个字段或是属性映射的细节信息

name:属性允许显式地指定列的名称

length:属性为用于映射一个值,特别为一个字符串值的列的大小

nullable:属性允许当生成模式时,一个列可以被标记为非空

unique:属性允许列中只能含有唯一的内容

 

五)在src/main/resources下创建hibernate的配置,文件名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>
    <!-- mysql配置
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/xm</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">admin</property>
    -->
    
    <!-- oracle -->
    <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:ORCL</property>
    <property name="hibernate.connection.username">oysept</property>
    <property name="hibernate.connection.password">oysept</property>
    
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.format_sql">true</property>
    
    <!-- 实体类注册 -->
    <mapping class="com.oyj.hibernate.entity.EmployeeEntity" />
    
</session-factory>
</hibernate-configuration> 

 

第六步)在src/main/test文件夹下创建一个数据添加的测试类AddEmployee.java

代码如下:

package com.oyj.hibernate;

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

import com.oyj.hibernate.entity.EmployeeEntity;

public class AddEmployee {

	public static void main(String[] args) {
        SessionFactory factory = null;
        Session session = null;
        try {
            // 创建SessionFactory
            factory = new Configuration().configure().buildSessionFactory();
            // 创建Session
            session= factory.openSession();
        	
            session.beginTransaction(); // 开启事务
            
            EmployeeEntity entity = new EmployeeEntity();
            entity.setUserID(999999);
            entity.setUserName("cb");
            entity.setSex(1);
            
            session.save(entity); // 持久化用户信息
            
            session.getTransaction().commit(); // 提交事务
        } catch (Exception e) {
            e.printStackTrace();
            session.getTransaction().rollback();; // 事务滚
        } finally {
            if (session != null) {
                session.close();
            }
            if (factory != null) {
                factory.close();
            }
        }
    }
}

 

第七步:在src/main/test文件夹下创建一个数据查询测试类QueryEmployee.java

代码如下:

package com.oyj.hibernate;

import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.hibernate.transform.Transformers;

import com.oyj.hibernate.entity.EmployeeEntity;

public class QueryEmployee {

    public static void main(String[] args) {
        firstMethod(); // 方式一
		
        secondMethod(); // 方式二
		
        threeMethod(); // 方式三
    }
	
    public static void firstMethod() {
        SessionFactory factory = null;
        Session session = null;
        try {
            factory = new Configuration().configure().buildSessionFactory();
            session = factory.openSession();
			
            System.out.println("第一种查询方式, hibernate HQL查询----------begin----------");
            // 第一种方式查询, hibernate HQL查询, 以实体类信息代替数据库表中的信息
            String hql = "select e from EmployeeEntity e";
            Query<EmployeeEntity> query = session.createQuery(hql);
            // 默认返回的数据是List<Object[]>
            List<EmployeeEntity> list = query.getResultList();
            for (EmployeeEntity entity : list) {
            System.out.println(entity.getUserID() + "----" + entity.getUserName() + "----" + entity.getSex());
            }
            System.out.println("第一种查询方式, hibernate HQL查询----------end----------");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("==>数据查询失败!");
        } finally {
            if (session != null) {
                session.close();
            }
            if (factory != null) {
                factory.close();
            }
        }
    }

    public static void secondMethod() {
        SessionFactory factory = null;
        Session session = null;
        try {
            factory = new Configuration().configure().buildSessionFactory();
            session = factory.openSession();
			
            System.out.println("第二种查询方式, 原生sql查询----------begin----------");
            // 第二种方式查询, 原生sql查询
            String sql = "select e.userid, e.username, e.sex from employee e";
            Query query = session.createSQLQuery(sql);
            // 默认返回的数据是List<Object[]>
            List<Object[]> resultList = query.getResultList();
            Object[] objs;
            for (int i=0; i < resultList.size(); i++) {
                objs = (Object[])resultList.get(i);
                // 根据sql字段查询的顺序打印
                System.out.println(objs[0] + "----" + objs[1] + "----" + objs[2]);
            }
            System.out.println("第二种查询方式, 原生sql查询----------end----------");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("==>数据查询失败!");
        } finally {
            if (session != null) {
                session.close();
            }
            if (factory != null) {
                factory.close();
            }
        }
    }
	
    public static void threeMethod() {
        SessionFactory factory = null;
        Session session = null;
        try {
            factory = new Configuration().configure().buildSessionFactory();
            session = factory.openSession();
			
            System.out.println("第三种查询方式, 原生sql查询, 返回List<Map<Object, Object>>----------begin----------");
            // 第三种方式查询, 原生sql查询, 返回值不一样
            String sql = "select e.userid, e.username, e.sex from employee e";
            Query query = session.createSQLQuery(sql);
            // 设置返回的参数格式为List<Map<Object, Object>>
			query.unwrap(NativeQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
            // 默认返回的数据是List<Object[]>
            List<Map<Object, Object>> resultList = query.getResultList();
			
            // map返回方式性能比object低, 不推荐使用了
            for (Map<Object, Object> map : resultList) {
                // map key
                System.out.println(map.get("USERID") + "----" + map.get("USERNAME") + "----" + map.get("SEX"));
            }
            System.out.println("第三种查询方式, 原生sql查询, 返回List<Map<Object, Object>>----------end----------");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("==>数据查询失败!");
        } finally {
            if (session != null) {
                session.close();
            }
            if (factory != null) {
                factory.close();
            }
        }
    }
}

第一种查询方式, hibernate HQL查询效果图打印:

 

第二种查询方式, 原生sql查询效果图打印,该方式缺点在于,查询的字段顺序要求比较严格:

 

第三种查询方式, 原生sql查询, 返回List<Map<Object, Object>>效果图打印:

 

识别二维码关注个人微信公众号

本章完结,待续,欢迎转载!
 
本文说明:该文章属于原创,如需转载,请标明文章转载来源!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值