互联网分布式应用之SpringDataJPA

SpringDataJPA

Java 是第一大编程语言和开发平台。它有助于企业降低成本、缩短开发周期、推动创新以及改善应用服务。如今全球有数百万开发人员运行着超过 51 亿个 Java 虚拟机,Java 仍是企业和开发人员的首选开发平台。
  

课程内容的介绍

1. Spring整合Hibernate
2. Spring整合HibernateJPA
3. SpringDataJPA介绍
4. SpringBoot整合SpringDataJPA
  
Spring Data JPA:Spring Data JPA 是 Spring Data 项目下的一个模块。提供了一套基于 JPA标准操作数据库的简化方案。底层默认的是依赖 Hibernate JPA 来实现的。
Spring Data JPA 的技术特点:我们只需要定义接口并集成 Spring Data JPA 中所提供的接口就可以了。不需要编写接口实现类。
  

一、Spring整合Hibernate

1. 创建项目
创建一个普通的Maven项目即可。

   
2.添加相关的依赖
    <dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>5.1.6.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.1.6.RELEASE</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.8</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.11</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-core</artifactId><version>5.0.7.Final</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.1.6.RELEASE</version></dependency></dependencies>
   
3. 添加相关的配置文件
添加数据库的配置文件和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:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd
"><!-- 引入db.properties文件 --><context:property-placeholder location="classpath:db.properties" /><!-- 创建druid 的数据源 --><bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource"><property name="url" value="${jdbc.url}" /><property name="driverClassName" value="${jdbc.driver}" /><property name="username" value="${jdbc.username}" /><property name="password"  value="${jdbc.password}" /></bean><!-- 配置Hibernate的SessionFactory对象 --><bean class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" id="sessionFactory"><!-- 关联数据源 --><property name="dataSource" ref="dataSource"/><!-- 配置Hibernate的属性信息 --><property name="hibernateProperties"><props><prop key="show_sql">true</prop><prop key="hibernate.hbm2ddl.auto">update</prop></props></property><!-- 扫描路径 --><property name="packagesToScan"><list><value>com.bobo.pojo</value></list></property></bean><!-- 配置HibernateTemplate对象 --><bean class="org.springframework.orm.hibernate5.HibernateTemplate" id="hibernateTemplate"><property name="sessionFactory" ref="sessionFactory"/></bean><!--  配置事务管理--><bean class="org.springframework.orm.hibernate5.HibernateTransactionManager" id="transactionManager"><property name="sessionFactory" ref="sessionFactory" /></bean><!-- 配置开启事务注解 --><tx:annotation-driven transaction-manager="transactionManager" /><!-- 配置扫描路径 --><context:component-scan base-package="com.bobo" />
</beans>
     
4. 创建POJO
和表结构中的t_user表对应即可。
package com.bobo.pojo;import javax.persistence.*;
import java.io.Serializable;@Entity
@Table(name="t_user")
public class Users implements Serializable {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name="user_id")private Integer userId;@Column(name="user_name")private String userName;@Column(name="real_name")private String realName;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 String getRealName() {return realName;}public void setRealName(String realName) {this.realName = realName;}}
   
5. 创建持久层
定义持久层接口,定义要实现的相关的方法。
package com.bobo.dao;import com.bobo.pojo.Users;import java.util.List;public interface IUserDao {void insertUsers(Users users);void updateUsers(Users users);void deleteUsers(Users users);Users selectUsersById(Integer userId);List<Users> selectUsersByName(String userName);List<Users> selectUsersByNameUseSQL(String userName);List<Users> selectUsersByNameUseCriteria(String userName);
}
package com.bobo.dao.impl;import com.bobo.dao.IUserDao;
import com.bobo.pojo.Users;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;import java.util.List;@Repository
public class UserDaoImpl implements IUserDao {@Autowiredprivate HibernateTemplate template;@Overridepublic void insertUsers(Users users) {this.template.save(users);}@Overridepublic void updateUsers(Users users) {this.template.update(users);}@Overridepublic void deleteUsers(Users users) {this.template.delete(users);}@Overridepublic Users selectUsersById(Integer userId) {return this.template.get(Users.class,userId);}@Overridepublic List<Users> selectUsersByName(String userName) {// 我们要执行特殊的查询操作 我们需要获取对应的Session对象Session session = this.template.getSessionFactory().getCurrentSession();// 通过Session对象创建Query对象 HQL 语句Query query = session.createQuery(" from Users where userName = :abc");Query queryTemp = query.setString("abc", userName);return queryTemp.list();}@Overridepublic List<Users> selectUsersByNameUseSQL(String userName) {// 我们要执行特殊的查询操作 我们需要获取对应的Session对象Session session = this.template.getSessionFactory().getCurrentSession();// 通过Session对象创建Query对象 SQL 语句Query query = session.createSQLQuery("select * from t_user where user_name = ?").addEntity(Users.class).setString(0, userName);return query.list();}@Overridepublic List<Users> selectUsersByNameUseCriteria(String userName) {Session session = this.template.getSessionFactory().getCurrentSession();Criteria criteria = session.createCriteria(Users.class);criteria.add(Restrictions.eq("userName",userName));return criteria.list();}
}
     
6. 单元测试
package com.bobo.test;import com.bobo.dao.IUserDao;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test1 {@Autowiredprivate IUserDao dao;@Test@Transactional@Rollback(false)public void testInsertUser(){Users user = new Users();user.setUserName("Tom");user.setRealName("张三丰");dao.insertUsers(user);}@Test@Transactionalpublic void testQuery1(){Users users = this.dao.selectUsersById(22);System.out.println(users);}@Test@Transactionalpublic void testQuery2(){List<Users> list = this.dao.selectUsersByNameUseSQL("Tom");for (Users users : list) {System.out.println(users);}}}
  

  

  

二、Spring整合HibernateJPA

现如今的ORM框架还是比较多的比如Hibernate,TopLink以及OpenJPA等等,为了简化ORM框架的使用,JPA随之产生。
JPA是Java Persistence API的简称,中文名Java持久层API,由 Sun 公司提供了一对对于持久层操作的标准(接口+文档),说白了就是在各种ORM框架之上封装了一套API实现统一操作。同时又依赖各种ORM框架去实现。hibernate3.2版本后提供了对JPA的实现。
  
1. 创建项目
创建一个普通的Maven项目即可。

    
2. 添加相关的依赖
    <dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>5.1.6.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.1.6.RELEASE</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.8</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.11</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-entitymanager</artifactId><version>5.0.7.Final</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.1.6.RELEASE</version></dependency></dependencies>
   
3. 添加相关的配置文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/logistics?characterEncoding=utf-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
     
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:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd
"><!-- 引入db.properties文件 --><context:property-placeholder location="classpath:db.properties" /><!-- 创建druid 的数据源 --><bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource"><property name="url" value="${jdbc.url}" /><property name="driverClassName" value="${jdbc.driver}" /><property name="username" value="${jdbc.username}" /><property name="password"  value="${jdbc.password}" /></bean><!-- 配置Hibernate的SessionFactory对象 --><bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="sessionFactory"><!-- 关联数据源 --><property name="dataSource" ref="dataSource"/><!-- 配置Hibernate的属性信息 --><property name="jpaVendorAdapter"><bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"><property name="database" value="MYSQL"/><property name="generateDdl" value="true"/><property name="showSql" value="true"/></bean><!--<props><prop key="show_sql">true</prop><prop key="hibernate.hbm2ddl.auto">update</prop></props>--></property><!-- 扫描路径 --><property name="packagesToScan"><list><value>com.bobo.pojo</value></list></property></bean><!--  配置事务管理--><bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager"><property name="entityManagerFactory" ref="sessionFactory" /></bean><!-- 配置开启事务注解 --><tx:annotation-driven transaction-manager="transactionManager" /><!-- 配置扫描路径 --><context:component-scan base-package="com.bobo" />
</beans>
  
4. 创建POJO
package com.bobo.pojo;import javax.persistence.*;
import java.io.Serializable;@Entity
@Table(name="t_user")
public class Users implements Serializable {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name="user_id")private Integer userId;@Column(name="user_name")private String userName;@Column(name="real_name")private String realName;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 String getRealName() {return realName;}public void setRealName(String realName) {this.realName = realName;}@Overridepublic String toString() {return "Users{" +"userId=" + userId +", userName='" + userName + '\'' +", realName='" + realName + '\'' +'}';}
}
  
5. 创建持久层
package com.bobo.dao;import com.bobo.pojo.Users;import java.util.List;public interface IUserDao {void insertUsers(Users users);void updateUsers(Users users);void deleteUsers(Users users);Users selectUsersById(Integer userId);List<Users> selectUsersByName(String userName);List<Users> selectUsersByNameUseSQL(String userName);List<Users> selectUsersByNameUseCriteria(String userName);
}
    
实现类
package com.bobo.dao.impl;import com.bobo.dao.IUserDao;
import com.bobo.pojo.Users;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;@Repository
public class UserDaoImpl implements IUserDao {@PersistenceContext(name = "entityManagerFactory")private EntityManager manager;@Overridepublic void insertUsers(Users users) {manager.persist(users);}@Overridepublic void updateUsers(Users users) {manager.merge(users);}@Overridepublic void deleteUsers(Users users) {users = this.selectUsersById(users.getUserId());manager.remove(users);}@Overridepublic Users selectUsersById(Integer userId) {return manager.find(Users.class,userId);}@Overridepublic List<Users> selectUsersByName(String userName) {return manager.createQuery(" from Users where userName = :abc").setParameter("abc",userName).getResultList();}@Overridepublic List<Users> selectUsersByNameUseSQL(String userName) {return manager.createNativeQuery("select * from t_user where user_name = ?",Users.class).setParameter(1,userName).getResultList();}@Overridepublic List<Users> selectUsersByNameUseCriteria(String userName) {CriteriaBuilder builder = manager.getCriteriaBuilder();CriteriaQuery<Users> query = builder.createQuery(Users.class);Root<Users> root = query.from(Users.class);Predicate cate = builder.equal(root.get("userName"), userName);query.where(cate);TypedQuery<Users> typedQuery = manager.createQuery(query);return typedQuery.getResultList();}
}
    
6. 单元测试
package com.bobo.test;import com.bobo.dao.IUserDao;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test1 {@Autowiredprivate IUserDao dao;@Test@Transactional@Rollback(false)public void testInsertUser(){Users user = new Users();user.setUserName("Mic");user.setRealName("李逵");dao.insertUsers(user);}@Test@Transactionalpublic void testQuery1(){Users users = this.dao.selectUsersById(22);System.out.println(users);}@Test@Transactionalpublic void testQuery2(){List<Users> list = this.dao.selectUsersByNameUseSQL("Tom");for (Users users : list) {System.out.println(users);}}}
  

  

  

三、SpringDataJPA介绍

1. 入门案例
1.1 创建项目
创建一个普通的Maven项目。
  
1.2 添加相关的依赖
    <dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>5.1.6.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.1.6.RELEASE</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.8</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.11</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-entitymanager</artifactId><version>5.0.7.Final</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.1.6.RELEASE</version></dependency><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-jpa</artifactId><version>1.9.0.RELEASE</version></dependency></dependencies>
  
1.3 添加配置文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/logistics?characterEncoding=utf-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
     
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:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:jpa="http://www.springframework.org/schema/data/jpa"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/data/jpahttp://www.springframework.org/schema/data/jpa/spring-jpa.xsd
"><!-- 引入db.properties文件 --><context:property-placeholder location="classpath:db.properties" /><!-- 创建druid 的数据源 --><bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource"><property name="url" value="${jdbc.url}" /><property name="driverClassName" value="${jdbc.driver}" /><property name="username" value="${jdbc.username}" /><property name="password"  value="${jdbc.password}" /></bean><!-- 配置Hibernate的SessionFactory对象 id必须得是 : entityManagerFactory --><bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"id="entityManagerFactory"><!-- 关联数据源 --><property name="dataSource" ref="dataSource"/><!-- 配置Hibernate的属性信息 --><property name="jpaVendorAdapter"><bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"><property name="database" value="MYSQL"/><property name="generateDdl" value="true"/><property name="showSql" value="true"/></bean><!--<props><prop key="show_sql">true</prop><prop key="hibernate.hbm2ddl.auto">update</prop></props>--></property><!-- 扫描路径 --><property name="packagesToScan"><list><value>com.bobo.pojo</value></list></property></bean><!--  配置事务管理--><bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager"><property name="entityManagerFactory" ref="entityManagerFactory" /></bean><!-- 配置开启事务注解 --><tx:annotation-driven transaction-manager="transactionManager" /><!-- 配置扫描路径 --><context:component-scan base-package="com.bobo" /><!--  Spring Data Jpa 配置--><!-- 配置Dao的扫描 --><jpa:repositories base-package="com.bobo.dao" />
</beans>
  
1.4 创建POJO对象
package com.bobo.pojo;import javax.persistence.*;
import java.io.Serializable;@Entity
@Table(name="t_user")
public class Users implements Serializable {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name="user_id")private Integer userId;@Column(name="user_name")private String userName;@Column(name="real_name")private String realName;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 String getRealName() {return realName;}public void setRealName(String realName) {this.realName = realName;}@Overridepublic String toString() {return "Users{" +"userId=" + userId +", userName='" + userName + '\'' +", realName='" + realName + '\'' +'}';}
}
  
1.5 创建持久层
package com.bobo.dao;import com.bobo.pojo.Users;
import org.springframework.data.jpa.repository.JpaRepository;public interface UserDao extends JpaRepository<Users,Integer> {}
     
1.6 单元测试
package com.bobo.test;import com.bobo.dao.UserDao;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test1 {@Autowiredprivate UserDao dao;@Test@Transactional@Rollback(false)public void test1(){Users user = new Users();user.setUserName("admin-jpa");user.setRealName("测试");dao.save(user);}
}
  

  

  
2. Repository接口
public interface Repository<T, ID extends Serializable> {
}
    
Repository 接口是 Spring Data JPA 中为我我们提供的所有接口中的顶层接口,而且是个标志接口,Repository 提供了两种查询方式的支持。
1)基于方法名称命名规则查询
2)基于@Query 注解查询
    
2.1 基于方法名称命名规则查询

      
package com.bobo.dao;import com.bobo.pojo.Users;
import org.springframework.data.repository.Repository;import javax.persistence.criteria.CriteriaBuilder;
import java.util.List;/*** Repository接口的使用*/
public interface UserDaoRepository extends Repository<Users, Integer> {List<Users> findByUserNameIs(String string);List<Users> findByUserNameLike(String username);List<Users> findByUserNameAndRealNameIs(String name,String realName);
}
    
测试代码
package com.bobo.test;import com.bobo.dao.UserDaoRepository;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test2 {@Autowiredprivate UserDaoRepository dao;@Test@Transactional@Rollback(false)public void query1(){List<Users> list = this.dao.findByUserNameIs("Tom");for (Users users : list) {System.out.println(users);}}@Test@Transactional@Rollback(false)public void query2(){List<Users> list = this.dao.findByUserNameLike("Tom");for (Users users : list) {System.out.println(users);}}@Test@Transactional@Rollback(false)public void query3(){List<Users> list = this.dao.findByUserNameAndRealNameIs("Tom","张三丰");for (Users users : list) {System.out.println(users);}}
}
  

   
2.2 基于@Query 注解查询
通过上面的命令的方式使用的情况,如果查询条件比较复杂的情况下,那么方法的名称会很长,不是很方便而且容易出错,这时我们可以通过@Query注解来实现。
  
2.2.1 JPQL语句
JPQL:是通过Hibernate的HQL语句演变而来的,他和HQL语句很相似。
package com.bobo.dao;import com.bobo.pojo.Users;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;import java.util.List;/*** Repository接口的使用* @Query*    JPQL语句*    SQL语句*    更新操作*/
public interface UserDaoRepository2 extends Repository<Users, Integer> {@Query(value = " from Users where userName =?")List<Users> queryUsersByNameUseJPQL(String name);@Query(value = " from Users where userName like ?")List<Users> queryUserLikeNameUseJPQL(String name);@Query(value = " from Users where userName= ? and realName = ?")List<Users> queryUserByNameAndRealName(String userName,String realName);}
     
单元测试
package com.bobo.test;import com.bobo.dao.UserDaoRepository;
import com.bobo.dao.UserDaoRepository2;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test3 {@Autowiredprivate UserDaoRepository2 dao;@Test@Transactional@Rollback(false)public void query1(){List<Users> list = this.dao.queryUsersByNameUseJPQL("Tom");for (Users users : list) {System.out.println(users);}}@Test@Transactional@Rollback(false)public void query2(){List<Users> list = this.dao.queryUserLikeNameUseJPQL("Tom");for (Users users : list) {System.out.println(users);}}@Test@Transactional@Rollback(false)public void query3(){List<Users> list = this.dao.queryUserByNameAndRealName("Tom","张三丰");for (Users users : list) {System.out.println(users);}}
}
  
2.2.2 SQL语句
声明接口
package com.bobo.dao;import com.bobo.pojo.Users;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;import java.util.List;/*** Repository接口的使用* @Query*    JPQL语句*    SQL语句*    更新操作*/
public interface UserDaoRepository3 extends Repository<Users, Integer> {// 在使用@Query注解 查询SQL语句的时候 nativeQuery默认是false,我们需要设置为true@Query(value = "select * from t_user where user_name=?",nativeQuery = true)List<Users> queryUsersByNameUseSQL(String name);@Query(value = "select * from t_user where user_name like ?" ,nativeQuery = true)List<Users> queryUserLikeNameUseSQL(String name);@Query(value = "select * from t_user where user_name = ? and real_name = ?" , nativeQuery = true)List<Users> queryUserByNameAndRealName(String userName,String realName);}
    
单元测试
package com.bobo.test;import com.bobo.dao.UserDaoRepository2;
import com.bobo.dao.UserDaoRepository3;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test4 {@Autowiredprivate UserDaoRepository3 dao;@Test@Transactional@Rollback(false)public void query1(){List<Users> list = this.dao.queryUsersByNameUseSQL("Tom");for (Users users : list) {System.out.println(users);}}@Test@Transactional@Rollback(false)public void query2(){List<Users> list = this.dao.queryUserLikeNameUseSQL("Tom");for (Users users : list) {System.out.println(users);}}@Test@Transactional@Rollback(false)public void query3(){List<Users> list = this.dao.queryUserByNameAndRealName("Tom","张三丰");for (Users users : list) {System.out.println(users);}}
}
  

   
2.2.3 完成更新数据
@Query注解可以完成数据更新操作,但是不能实现数据的添加和删除操作。
@Query(value = "update Users set userName = ? where userId=?")
@Modifying// 被@Modifying修饰的方法是一个更新操作
void updateUserNameById(String userName,Integer userId);
  
测试
@Test
@Transactional
@Rollback(false)
public void updateTest(){this.dao.updateUserNameById("Tommm",25);
}
  

  
3. CrudRepository接口
CrudRepository接口继承自Repository接口,所以Repository接口具有的功能CrudRepository接口都具有,而且又扩展了CRUD相关的功能。
@NoRepositoryBean
public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {<S extends T> S save(S var1);<S extends T> Iterable<S> save(Iterable<S> var1);T findOne(ID var1);boolean exists(ID var1);Iterable<T> findAll();Iterable<T> findAll(Iterable<ID> var1);long count();void delete(ID var1);void delete(T var1);void delete(Iterable<? extends T> var1);void deleteAll();
}
    
应用声明接口
/**
* CrudRepository接口的使用
*/
public interface UserDaoCrudRepository extends CrudRepository<Users,Integer> {
}
     
单元测试
package com.bobo.test;import com.bobo.dao.UserDaoCrudRepository;
import com.bobo.dao.UserDaoRepository3;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.experimental.theories.suppliers.TestedOn;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.support.CustomSQLErrorCodesTranslation;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test5 {@Autowiredprivate UserDaoCrudRepository dao;/*** 添加数据*/@Testpublic void test1(){Users user = new Users();user.setRealName("成龙");user.setUserName("chengnong");dao.save(user);}/*** 批量添加数据*/@Testpublic void test2(){List<Users> list = new ArrayList<>();for (int i = 0; i < 10; i++) {Users user = new Users();user.setRealName("成龙"+i);user.setUserName("chengnong"+i);list.add(user);}dao.save(list);}/*** 查询单条数据*/@Testpublic void test3(){Users user = dao.findOne(25);System.out.println(user);}/*** 查询所有的数据*/@Testpublic void test4(){Iterable<Users> list = dao.findAll();Iterator<Users> iterator = list.iterator();while(iterator.hasNext()){Users user = iterator.next();System.out.println(user);}}/*** 删除数据*/@Testpublic void delete1(){dao.delete(32);}/*** 更新数据*/@Testpublic void update1(){// 根据save方法来实现 如果Users对象的userId属性不为空则updateUsers user = dao.findOne(34);user.setUserName("hahahaha");dao.save(user);}/*** 更新数据 方式二*/@Test@Transactional@Rollback(false)public void update2(){Users user = dao.findOne(34);user.setUserName("aaaa"); // User 是一个持久化的状态}
}
  
4.PagingAndSortingRepository接口
PagingAndSortingRepository继承自CrudRepository接口,那么显然PagingAndSortingRepository就具备了CrudRepository接口的相关的功能,同时也扩展了分页和排序的功能。
@NoRepositoryBean
public interface PagingAndSortingRepository<T, ID extends Serializable> extends CrudRepository<T, ID> {// 排序的支持Iterable<T> findAll(Sort var1);// 分页的支持Page<T> findAll(Pageable var1);
}
  
创建接口文件
package com.bobo.dao;import com.bobo.pojo.Users;
import org.springframework.data.repository.PagingAndSortingRepository;/*** PagingAndSortingRepository接口的使用*    新增的功能是*       分页*       排序*    注意本接口不支持条件查询*/
public interface UserDaoPageAndSortRepository extends PagingAndSortingRepository<Users,Integer> {
}
  
分页测试
package com.bobo.test;import com.bobo.dao.UserDaoCrudRepository;
import com.bobo.dao.UserDaoPageAndSortRepository;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test6 {@Autowiredprivate UserDaoPageAndSortRepository dao;/*** 分页查询*/@Testpublic void test1(){int page = 1; // page:当前分页的索引  从0开始int size = 5; // size:每页显示的条数PageRequest pageable = new PageRequest(page,size);Page<Users> pages = dao.findAll(pageable);System.out.println("总的条数:" + pages.getTotalElements());System.out.println("总的页数:" + pages.getTotalPages());List<Users> list = pages.getContent();for (Users user : list) {System.out.println(user);}}
}
  

  
排序功能
    /*** 排序*/@Testpublic void test2(){// Sort.Direction.DESC 降序 ASC 升序Sort sort = new Sort(Sort.Direction.DESC,"userId");List<Users> list = (List<Users>) this.dao.findAll(sort);for (Users users : list) {System.out.println(users);}}
    

  
多条件排序
    /*** 多条件排序*/@Testpublic void test3(){Sort.Order order1 = new Sort.Order(Sort.Direction.DESC,"realName");Sort.Order order2 = new Sort.Order(Sort.Direction.ASC,"userId");Sort sort = new Sort(order1,order2);List<Users> list = (List<Users>) this.dao.findAll(sort);for (Users users : list) {System.out.println(users);}}
  

  
5. JpaRepository接口
JpaRepository接口是我们开发时使用最多接口,其特点是可以帮助我们将其他接口的方法的返回值做适配处理,可以使我们在开发的时候更方便的使用这些方法。
@NoRepositoryBean
public interface JpaRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID> {List<T> findAll();List<T> findAll(Sort var1);List<T> findAll(Iterable<ID> var1);<S extends T> List<S> save(Iterable<S> var1);void flush();<S extends T> S saveAndFlush(S var1);void deleteInBatch(Iterable<T> var1);void deleteAllInBatch();T getOne(ID var1);
}
  
6. JpaSpecificationExecutor
提供的有多条件查询,并支持分页和排序功能,此接口不能单独使用,需要和其他的接口一块使用。
/**
* JpaSpecificationExecutor的使用
* JpaSpecificationExecutor 是不能够单独使用的。需要配置JPA中的其他的接口一块来使用
*/
public interface UserDaoSpecfication extends JpaRepository<Users,Integer>, JpaSpecificationExecutor {
}
     
6.1 单条件查询
package com.bobo.test;import com.bobo.dao.UserDaoSpecfication;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test7 {@Autowiredprivate UserDaoSpecfication dao;@Testpublic void test1(){Specification<Users> speci = new Specification<Users>() {/*** 定义查询条件* @param root 根对象  封装查询条件的对象* @param criteriaQuery 基本的查询* @param criteriaBuilder 创建查询条件* @return*/@Overridepublic Predicate toPredicate(Root<Users> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {Predicate pre = criteriaBuilder.equal(root.get("userName"),"Tommm");return pre;}};List<Users> list = dao.findAll(speci);for (Users users : list) {System.out.println(users);}}
}
  

  
6.2 多条件
    /*** 多条件查询*/@Testpublic void test2(){Specification<Users> spec = new Specification<Users>() {/*** 指定查询的条件* @param root* @param criteriaQuery* @param criteriaBuilder* @return*/@Overridepublic Predicate toPredicate(Root<Users> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {List<Predicate> list = new ArrayList<>();list.add(criteriaBuilder.equal(root.get("userName"),"Tommm"));list.add(criteriaBuilder.equal(root.get("realName"),"张三丰"));Predicate[] arr = new Predicate[list.size()];return criteriaBuilder.and(list.toArray(arr));}};List<Users> list = dao.findAll(spec);for (Users users : list) {System.out.println(users);}}
  

  
6.3 分页
    /*** 单条件+分页*/@Testpublic void test3(){Specification<Users> speci = new Specification<Users>() {/*** 定义查询条件* @param root 根对象  封装查询条件的对象* @param criteriaQuery 基本的查询* @param criteriaBuilder 创建查询条件* @return*/@Overridepublic Predicate toPredicate(Root<Users> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {Predicate pre = criteriaBuilder.equal(root.get("userName"),"Tommm");return pre;}};Pageable pagealbe = (Pageable) new PageRequest(0,3);Page page = dao.findAll(speci, pagealbe);System.out.println(page.getTotalElements());System.out.println(page.getTotalPages());List content = page.getContent();System.out.println(content);}
  

  
6.4 排序
    /*** 单条件+排序*/@Testpublic void test4(){Specification<Users> speci = new Specification<Users>() {/*** 定义查询条件* @param root 根对象  封装查询条件的对象* @param criteriaQuery 基本的查询* @param criteriaBuilder 创建查询条件* @return*/@Overridepublic Predicate toPredicate(Root<Users> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {Predicate pre = criteriaBuilder.equal(root.get("userName"),"Tommm");return pre;}};Sort sort = new Sort(Sort.Direction.DESC,"userId");List<Users> list = dao.findAll(speci, sort);System.out.println(list);}
  

  
6.5 分页和排序
    /*** 单条件+分页 + 排序*/@Testpublic void test5(){Specification<Users> speci = new Specification<Users>() {/*** 定义查询条件* @param root 根对象  封装查询条件的对象* @param criteriaQuery 基本的查询* @param criteriaBuilder 创建查询条件* @return*/@Overridepublic Predicate toPredicate(Root<Users> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {Predicate pre = criteriaBuilder.equal(root.get("userName"),"Tommm");return pre;}};Sort sort = new Sort(Sort.Direction.DESC,"userId");// 封装分页对象的时候我们可以直接指定 排序的规则Pageable pagealbe = (Pageable) new PageRequest(0,3,sort);Page page = dao.findAll(speci, pagealbe);System.out.println(page.getTotalElements());System.out.println(page.getTotalPages());List content = page.getContent();System.out.println(content);}
  

  

四、SpringBoot整合SpringDataJPA

1. 添加依赖

  
2. 添加配置文件
# jdbc 的相关信息
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/logistics?
characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456# 配置连接池信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource# 配置jpa的相关参数
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
    
3. 创建POJO
package com.bobo.pojo;import javax.persistence.*;
import java.io.Serializable;@Table(name = "t_user")
@Entity
public class Users implements Serializable {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name="user_id")private Integer userId;@Column(name="user_name")private String usreName;@Column(name="real_name")private String realName;public Integer getUserId() {return userId;}public void setUserId(Integer userId) {this.userId = userId;}public String getUsreName() {return usreName;}public void setUsreName(String usreName) {this.usreName = usreName;}public String getRealName() {return realName;}public void setRealName(String realName) {this.realName = realName;}
}
  
4. 创建接口
package com.bobo.dao;import com.bobo.pojo.Users;
import org.springframework.data.jpa.repository.JpaRepository;public interface UsersRepository extends JpaRepository<Users,Integer> {
}
  
5. 测试
package com.bobo;import com.bobo.dao.UsersRepository;
import com.bobo.pojo.Users;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
class SpringdatajpaSpringbootApplicationTests {@Autowiredprivate UsersRepository dao;@Testvoid contextLoads() {Users users = new Users();users.setUsreName("test1");users.setRealName("测试数据");dao.save(users);}}
  

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/232737.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

[C#]使用纯opencvsharp部署yolov8-onnx图像分类模型

【官方框架地址】 https://github.com/ultralytics/ultralytics.git 【算法介绍】 YOLOv8 是一个 SOTA 模型&#xff0c;它建立在以前 YOLO 版本的成功基础上&#xff0c;并引入了新的功能和改进&#xff0c;以进一步提升性能和灵活性。具体创新包括一个新的骨干网络、一个新…

CSS 压重按钮 效果

<template><view class="cont"><div class="container"><div class="pane"><!-- 选项1 --><label class="label" @click="handleOptionClick(0)":style="{ color: selectedOption ==…

精进单元测试技能 —— Pytest断言的艺术!

本篇文章主要是阐述Pytest在断言方面的应用。让大家能够了解和掌握Pytest针对断言设计了多种功能以适应在不同测试场景上使用。 了解断言的基础 在Pytest中&#xff0c;断言是通过 assert 语句来实现的。简单的断言通常用于验证预期值和实际值是否相等&#xff0c;例如&#…

FlinkSQL中【FULL OUTER JOIN】使用实例分析(坑)

Flink版本&#xff1a;flink1.14 最近有【FULL OUTER JOIN】场景的实时数据开发需求&#xff0c;想要的结果是&#xff0c;左右表来了数据都下发数据&#xff1b;左表存在的数据&#xff0c;右表进来可以关联下发&#xff08;同样&#xff0c;右表存在的数据&#xff0c;左表进…

FlinkAPI开发之数据合流

案例用到的测试数据请参考文章&#xff1a; Flink自定义Source模拟数据流 原文链接&#xff1a;https://blog.csdn.net/m0_52606060/article/details/135436048 概述 在实际应用中&#xff0c;我们经常会遇到来源不同的多条流&#xff0c;需要将它们的数据进行联合处理。所以…

Apache Paimon:Streaming Lakehouse is Coming

摘要&#xff1a;本文整理自阿里云智能开源表存储负责人&#xff0c;Founder of Paimon&#xff0c;Flink PMC 成员李劲松&#xff08;花名&#xff1a;之信&#xff09;、同程旅行大数据专家&#xff0c;Apache Hudi & Paimon Contributor 吴祥平、汽车之家大数据计算平台…

Mybatis实现增删改查的两种方式-配置文件/注解

环境准备 1.数据库表tb_brand -- 删除tb_brand表 drop table if exists tb_brand; -- 创建tb_brand表 create table tb_brand(-- id 主键id int primary key auto_increment,-- 品牌名称brand_name varchar(20),-- 企业名称company_name varchar(20),-- 排序字段ordered int…

[Flutter]WebPlatform上运行遇到的问题总结

[Flutter]WebPlatform上运行遇到的问题总结 目录 [Flutter]WebPlatform上运行遇到的问题总结 写在开头 正文 Q1、不兼容判断 Q2、跨域问题 其他 写在结尾 写在开头 Flutter项目已能在移动端完美使用后&#xff0c;想看看在桌面端等使用情况 基于Flutter3.0后已支持Wi…

前端框架中的状态管理(State Management)

聚沙成塔每天进步一点点 ⭐ 专栏简介 前端入门之旅&#xff1a;探索Web开发的奇妙世界 欢迎来到前端入门之旅&#xff01;感兴趣的可以订阅本专栏哦&#xff01;这个专栏是为那些对Web开发感兴趣、刚刚踏入前端领域的朋友们量身打造的。无论你是完全的新手还是有一些基础的开发…

李沐-《动手学深度学习》-- 01-预备知识

一、线性代数知识 1. 矩阵计算 a. 矩阵求导 ​ 当y和x分别为标量和向量时候&#xff0c;进行求导得到的矩阵形状&#xff0c;矩阵求导就是矩阵A中的每一个元素对矩阵B中的每一个元素求导 ​ 梯度指向的是值变化最大的方向 ​ 分子布局和分母布局&#xff1a; b. 常识 ax…

知识付费平台搭建?找明理信息科技,专业且高效

明理信息科技知识付费saas租户平台 在当今数字化时代&#xff0c;知识付费已经成为一种趋势&#xff0c;越来越多的人愿意为有价值的知识付费。然而&#xff0c;公共知识付费平台虽然内容丰富&#xff0c;但难以满足个人或企业个性化的需求和品牌打造。同时&#xff0c;开发和…

群晖NAS+DMS7.0以上版本+无docker机型安装zerotier

测试机型&#xff1a;群晖synology 218play / DSM版本为7.2.1 因218play无法安装docker&#xff0c;且NAS系统已升级为7.0以上版本&#xff0c;按zerotier官网说法无法安装zerotier, 不过还是可以通过ssh终端和命令方式安装zerotier。 1、在DSM新建文件夹 用于存放zerotier脚…

2023我的编程之旅-地质人的山和水

引言 大家好&#xff0c;我是搞地质的。外行人有的说我们游山玩水&#xff0c;有的说我们灰头土脸&#xff0c;也有的说我们不是科学。 而我说&#xff0c;这是一门穷极一生青春&#xff0c;值得奉献的行业。这是一门贴近民生&#xff0c;又拥抱自然的学科。他的真理性在于探…

进阶学习——Linux系统安全及应用

目录 一、系统安全加固 1.账号安全基本措施 1.1系统账号清理 1.1.1延伸 1.2密码安全控制 1.3命令历史限制 1.4终端自动注销 二、使用su命令切换用户 1.用途及用法 2.密码验证 3.限制使用su命令的用户 4.查看su操作记录 5.sudo&#xff08;superuse do&#xff09;…

stable diffusion 人物高级提示词(一)头部篇

一、女生发型 prompt描述推荐用法Long hair长发一定不要和 high ponytail 一同使用Short hair短发-Curly hair卷发-Straight hair直发-Ponytail马尾high ponytail 高马尾&#xff0c;一定不要和 long hair一起使用&#xff0c;会冲突Pigtails2条辫子-Braid辫子只写braid也会生…

数据库开发必备神器:DataGrip 工具安装指南

DataGrip是一款强大的跨平台数据库集成开发环境&#xff0c;全能数据库工具&#xff0c;支持多种数据库系统&#xff0c;包括MySQL&#xff0c;PostgreSQL&#xff0c;Oracle等&#xff1b;提供智能代码编辑功能&#xff0c;包括语法高亮、代码补全等&#xff0c;提升开发效率。…

Qt/QML编程学习之心得:Linux下Thread线程创建(26)

GUI设计中经常为了不将界面卡死,会用到线程Thread,而作为GUI设计工具,Qt也提供了一个这样的类,即QThread。 QThread对象管理程序中的一个控制线程。线程QThread开始在run()中执行。默认情况下,run()通过调用exec()启动事件循环,并在线程内运行Qt事件循环。 也可以通过…

YTM32的低功耗PowerDown模式及唤醒管理器WKU模块

文章目录 Introduction专门的唤醒源管理器WKU外部的唤醒引脚内部的触发信号 进入PowerDown模式的操作流进入低功耗模式配合使用的其他模块 性能指标低功耗电流唤醒时间 Conclusion Introduction YTM32的低功耗系统中有设计了多种工作模式&#xff0c;功耗从高到低&#xff0c;…

Spring之 国际化:i18n

1、i18n概述 国际化也称作i18n&#xff0c;其来源是英文单词 internationalization的首末字符i和n&#xff0c;18为中间的字符数。由于软件发行可能面向多个国家&#xff0c;对于不同国家的用户&#xff0c;软件显示不同语言的过程就是国际化。通常来讲&#xff0c;软件中的国…

2.6 KERNEL LAUNCH

图2.15在vecAdd函数中显示最终主机代码。此源代码完成了图2.6.中的骨架。2.12和2.15共同说明了一个简单的CUDA程序&#xff0c;该程序由主机代码和设备内核组成。该代码是硬接的&#xff0c;每个线程块使用256个线程。然而&#xff0c;使用的线程块的数量取决于向量&#xff08…