spring-利用hibernate的session来访问数据层

项目结构

这里写图片描述
实体类:

package entity;


    //创建一个与customer表对应的实体类,以便存放 Customer对象

public class Customer {
    private int id;
    private String name;
    private int age;
    public Customer(){}


    public Customer(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId(){
        return id;
    }

    public void setId(int id){
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

注意即使不需要,实体类最好生成一个default构造(无参构造)的空方法
映射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="entity.Customer" table="customer">
    <id name="id" column="CUST_ID">
    </id>
    <property name="name" column="NAME"></property>
    <property name="age" column="AGE"></property>
    </class>
</hibernate-mapping>

dao层:
接口:

package dao;

import entity.Customer;

public interface CustomerDao {
    public void insert(Customer customer);
    public Customer findByCustomerId(int custId);
}

实现类:

package dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import entity.Customer;
import utils.HibernateUtils;

public class HibetnateCustomerDao implements CustomerDao {




    public Session getSession() {
        //当前线程?
        return HibernateUtils.getSession();
    }

    @Override
    public void insert(Customer customer) {

            getSession().save(customer);
            System.out.println("saved ");

    }

    @Override
    public Customer findByCustomerId(int custId) {

    //    Customer customer = null;
    //  String hql=" from Customer where id=?";
    //   Query query=getSession().createQuery(hql).setParameter(0, custId);
    //    List list = query.list();
      //  customer = (Customer)list.get(0);
      //  return customer;
        Customer customer = null;
        customer = getSession().get(Customer.class, custId);
        return customer;

    }

}

这里面save也介绍了调用的query api,利用他传入hql(一定注意语法,之前就是语法错了bug没看出),注意
关于save方法的持久态问题没有考虑

此处调用的工具类:

package utils;

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

public class HibernateUtils {

     // 1.创建工厂对象;
     private static SessionFactory sessionFactory;

     // 2.初始化工厂对象;
     static {
     sessionFactory = new Configuration().configure().buildSessionFactory();
     }

     // 3.获得Session;
     public static Session getSession() {

     return sessionFactory.openSession();

     }


}

关于事物应该如何添加验证!需再看
service类
接口

package service;

import entity.Customer;

public interface CustomerService {
    public Customer findByCustomerId(int id);
    public void insert(Customer customer);

}

实现类

package service;

import dao.CustomerDao;
import entity.Customer;

public class CustomerServiceImpl implements CustomerService {

    private CustomerDao customerDao;

    public CustomerDao getCustomerDao() {
        return customerDao;
    }

    public void setCustomerDao(CustomerDao customerDao) {
        this.customerDao = customerDao;
    }

    @Override
    public Customer findByCustomerId(int id) {
        Customer customer=null;
        customer = customerDao.findByCustomerId(id);
        return customer;
    }

    @Override
    public void insert(Customer customer) {
        customerDao.insert(customer);

    }

}

spring核心配置文件、

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">



     <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" lazy-init="false">

        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>


    </bean>  

    <!-- 配置Spring声明式事务 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean> 

    <!-- 配置事务事务属性 -->
     <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    <!-- 配置事务切点,并把切点和事务属性关联起来 -->
    <aop:config>
        <aop:pointcut expression="execution(* dao.CustomerDao.*.*(..))" id="txPointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>

    <bean id="CustomerDao" class="dao.HibetnateCustomerDao">

    </bean>

    <bean id="CustomerService" class="service.CustomerServiceImpl">
        <property name="customerDao" ref="CustomerDao"></property>
    </bean>




</beans>

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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///spring_jdbc</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">shengri</property>

        <!--  2配置Hibernate信息  可选的-->
        <!-- 输出底层sql语句 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 输出底层sql语句格式 -->
        <property name="hibernate.format_sql">true</property>
        <!-- hibernate帮创建表,需要配置之后
            update:如果已经有表,更新,如果没有,创建
         -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!-- 配置数据库方言
            比如 在Mysql里面实现分页 是关键字limit 只能使用mysql里面
            在oracle里面, 则是rownum实现分页
            让hibernate框架识别不同数据库语句
        -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!--  3把映射文件放到核心中去 -->
        <mapping resource="entity/Customer.hbm.xml"/>


    </session-factory>

</hibernate-configuration>

也可以将hibernate核心配置文件放在spring中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">


        <bean id ="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driver_class">com.mysql.jdbc.Driver</property>
            <property name="jdbcUrl">jdbc:mysql:///spring_jdbc</property>
            <property name="user">root</property>
            <property name="password">shengri</property>
        </bean>


        <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" lazy-init="false">
            <property name="dataSource" ref="dataSource"></property>

        <!--  2配置Hibernate信息  可选的-->
        <!-- 输出底层sql语句 -->
            <property name="hibernate.show_sql">true</property>
        <!-- 输出底层sql语句格式 -->
            <property name="hibernate.format_sql">true</property>
        <!-- hibernate帮创建表,需要配置之后
            update:如果已经有表,更新,如果没有,创建
         -->
            <property name="hibernate.hbm2ddl.auto">update</property>
        <!-- 配置数据库方言
            比如 在Mysql里面实现分页 是关键字limit 只能使用mysql里面
            在oracle里面, 则是rownum实现分页
            让hibernate框架识别不同数据库语句
        -->
            <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!--  3把映射文件放到核心中去 -->
        <mapping resource="entity/Customer.hbm.xml"/>

    </bean>  

    <!-- 配置Spring声明式事务 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean> 

    <!-- 配置事务事务属性 -->
     <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    <!-- 配置事务切点,并把切点和事务属性关联起来 -->
    <aop:config>
        <aop:pointcut expression="execution(* dao.CustomerDao.*.*(..))" id="txPointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>

    <bean id="CustomerDao" class="dao.HibetnateCustomerDao">

    </bean>

    <bean id="CustomerService" class="service.CustomerServiceImpl">
        <property name="customerDao" ref="CustomerDao"></property>
    </bean>




</beans>

这种报错

org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 14 in XML document from class path resource [spring_hibernate.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 14; columnNumber: 66; cvc-complex-type.2.3: 元素 'property' 必须不含字符 [子级], 因为该类型的内容类型为“仅元素”。


这么配置没问题,不过应该是某个语法或是字符错误

或者这样配置
这里写图片描述

问题:关于事物管理 回滚等功能没有体现(与持久层结合观察) 做实验
然后用hibernatetemplate实现以上

猜你喜欢

转载自blog.csdn.net/weixin_38719347/article/details/81086804