其他分享
首页 > 其他分享> > springdata笔记2

springdata笔记2

作者:互联网

SpringData整合hibernate

CRUD操作:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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.fly</groupId>
    <artifactId>te-spring-data</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.16.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>5.2.16.Final</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <!--SpringData整合hibernate基于JPA规范:-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.5</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

</project>

jdbc.properties:

db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql:///mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false
db.username=root
db.password=root

applicationContext.xml:

<?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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 配置读取properties文件的工具类 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!-- 配置c3p0数据库连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${db.driver}"/>
        <property name="jdbcUrl" value="${db.url}"/>
        <property name="user" value="${db.username}"/>
        <property name="password" value="${db.password}"/>
    </bean>
    <!--=====================spring+hibernate=============================-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- hibernateProperties属性:配置与hibernate相关的内容,如显示sql语句,开启正向工程 -->
        <property name="hibernateProperties">
            <props>
                <!-- 显示当前执行的sql语句 -->
                <prop key="hibernate.show_sql">true</prop>
                <!-- 开启正向工程 -->
                <!--<prop key="hibernate.hbm2ddl.auto">update</prop>-->
            </props>
        </property>
        <!-- 扫描实体所在的包 -->
        <property name="packagesToScan">
            <list>
                <value>fly.pojo</value>
            </list>
        </property>
    </bean>
    <!-- 配置HibernateTemplate对象 -->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <!-- 配置Hibernate的事务管理器 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <!--===============================================================-->
   
    <!-- 配置开启注解事务处理 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <!-- 配置springIOC的注解扫描 -->
    <context:component-scan base-package="fly"/>
</beans>

UserDaoImpl:

@Repository
public class UserDaoImpl{
    @Autowired
    private HibernateTemplate hibernateTemplate;

    public User selectUsersById(Integer userId) {
        return this.hibernateTemplate.get(User.class, userId);
    }

    /**
     * HQL
     * 将原来的sql语句中的表与字段名换成对象与属性的名称
     */
    public User selectUsersByIdHQL(Integer userId) {
        //getCurrentSession:当前session必须要有事务边界,且只能处理唯一的一个事务。当事务提交或者回滚后session自动失效
        //openSession:每次都会打开一个新的session.加入每次使用多次。则获得的是不同session对象。使用完毕后我们需要手动的调用colse方法关闭session
        Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
        Query query = session.createQuery("from User where id = :id").setParameter("id", userId);
        List list = query.getResultList();
        return (User) list.get(0);
    }
    /**
     * SQL
     */
    public List<User> selectUsersByIdSQL(String username,String sex) {
        Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
        String sql = "select * from user where username like ? and sex = ?";
        Query query = session.createNativeQuery(sql,User.class).setParameter(1,"%"+username+"%").setParameter(2,sex);
        List list = query.getResultList();
        return list;
    }
    /**
     *基于JPA规范的CriteriaQuery查询
     * Criteria过时
     * (since 5.2) for Session, use the JPA Criteria
     */
    public List<User> selectUsersByIdQBC(String username) {
        Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
        CriteriaBuilder builder = session.getCriteriaBuilder();
        CriteriaQuery<User> criteriaQuery = builder.createQuery(User.class);
        Root<User> root = criteriaQuery.from(User.class);
        criteriaQuery.select(root);
        criteriaQuery.where(builder.like(root.get("username"),"%"+username+"%"));
        return session.createQuery(criteriaQuery).getResultList();
    }

    /**
     * 多参数
     */
    public List<User> selectUsersByIdQBC2(String username,String sex) {
        Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
        CriteriaBuilder builder = session.getCriteriaBuilder();
        CriteriaQuery<User> criteriaQuery = builder.createQuery(User.class);
        Root<User> root = criteriaQuery.from(User.class);

        List<Predicate> predicateList = new ArrayList<>();
        predicateList.add(builder.like(root.get("username"),"%"+username+"%"));
        predicateList.add(builder.equal(root.get("sex"),sex));
        criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));

        return session.createQuery(criteriaQuery).getResultList();
    }

}

spring + jpa

 <!--=======================spring+jpa========================================-->
    <!-- Spring整合JPA  配置EntityManagerFactory-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!-- hibernate相关的属性的注入 -->
                <!-- 配置数据库类型 -->
                <property name="database" value="MYSQL"/>
                <!-- 正向工程 自动创建表 -->
                <!--<property name="generateDdl" value="true"/>-->
                <!-- 显示执行的SQL -->
                <property name="showSql" value="true"/>
            </bean>
        </property>
        <!-- 扫描实体的包 -->
        <property name="packagesToScan">
            <list>
                <value>fly</value>
            </list>
        </property>
    </bean>
    <!-- 配置Hibernate的事务管理器 -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>
    <!--===============================================================-->

标签:username,criteriaQuery,springdata,spring,笔记,session,User,org
来源: https://www.cnblogs.com/fly-book/p/10409006.html