spring hibernate 整合 注解

Hibernate:

Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行。

spring:

spring是J2EE应用程序框架,是轻量级的IoC(控制反转)和AOP(面向切面编程)的容器框架,主要是针对JavaBean的生命周期进行管理的轻量级容器,可以单独使用,也可以和Struts框架,hibernate框架等组合使用。

IOC (控制反转)实现方式为DI(依赖注入):1️⃣setter注入 2️⃣ 构造器注入

数据库连接池

官方:数据库连接池(Connection pooling)是程序启动时建立足够的数据库连接,并将这些连接组成一个连接池,由程序动态地对池中的连接进行申请,使用,释放。
个人理解:创建数据库连接是一个很耗时的操作,也容易对数据库造成安全隐患。所以,在程序初始化的时候,集中创建多个数据库连接,并把他们集中管理,供程序使用,可以保证较快的数据库读写速度,还更加安全可靠。

spring架构图 :

spring架构图

以下是一个实现spring 和 hibernate 整合的小案例:

1.导入相关jar包

搜索jar包(中国仓库):【链接】MavenRepository:Search/Browse/Explore
https://mvnrepository.com/

这里写图片描述

2.User实体类 及其xml配置 (不需要解释)

User.java

package com.lanou.entity;

public class User {

    private int userId;
    private String userName;
    private String userPwd;
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    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;
    }

}

配置文件User.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- 关系映射将entity与table进行关联 -->
<hibernate-mapping>

    <class name="com.lanou.entity.User" table="USER">
        <id name="userId" type="int" column="USER_ID">
            <!-- 指明主键生成方式 -->
            <generator class="identity"></generator>
        </id>
        <property name="userName" column="USER_NAME" type="string"></property>
        <property name="userPwd" column="USER_Pwd" type="string"></property>
    </class>
</hibernate-mapping>
  1. dao层的UserDao类

UserDao.java

package com.lanou.dao;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.lanou.entity.User;

@Repository
public class UserDao {

    // 1.将sessionFactory注入到template
    // template 注入到 UserDao
    // spring 提供一个对象(CRUD操作)

    @Autowired
    HibernateTemplate template;

    public List<User> getAllUsers() {

        String hql = "from User";
        List<User> users = (List<User>) template.find(hql);

        return users;

    }
}

4.重点 配置applicationContext.xml

applicationContext.xml

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

    xsi:schemaLocation="  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context.xsd  
    http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans.xsd">


    <!-- ✨扫描注解 -->
    <context:component-scan base-package="com.lanou"></context:component-scan>

    <!--1.配置连接池-bean -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl"
            value="jdbc:mysql://localhost:3306/list?characterEncoding=utf-8" />
        <property name="user" value="root" />
        <property name="password" value="123456" />
    </bean>
    <!--2. 获取sessionFactory 通过spring获取hibernate提供的sessionFactory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <!-- 把c3p0注入到sessionFactory中 -->
        <property name="dataSource" ref="dataSource"></property>
        <!--hibernate 的基本配置 -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>

            </props>
        </property>
        <property name="mappingResources">
            <list>
                <value>com/lanou/entity/User.hbm.xml</value>
            </list>
        </property>
    </bean>
    <!-- 3.template配置  将sessionFactory注入到template -->
    <bean id="template" class="org.springframework.orm.hibernate4.HibernateTemplate">

    <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

</beans>

5.编写测试类

TestHibernate.java

package com.lanou.test;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.lanou.dao.UserDao;
import com.lanou.entity.User;

public class TestHibernate {

    /**
     * jUnit单元测试
     */

  @Test
    public void test() {

        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao=(UserDao) ac.getBean("userDao");
        List<User> users=userDao.getAllUsers();
        for (User user : users) {
            System.out.println(user.getUserName());
        }
    }
}

spring 注解注入

@Service用于标注业务层组件 (应用在serviceImpl类上)

@Controller用于标注控制层组件(应用在controller类上)

@Repository用于标注数据访问组件,即DAO组件

@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。

@Autowired 默认按类型装配

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值