1 JPA使用步骤

JPA=Java Persistence APIJava持久层APIJDK5引入JPA ORM目的:简化Java EE开发,整合ORM技术。JPA定义了JPQLJava Persistence Query Language)。

Spring Data JPA默认集成的JPA ProviderHibernate


a.pom.xml中增加JPA依赖

        <dependency>

            <groupId>org.springframework.bootgroupId>

            <artifactId>spring-boot-starter-data-jpaartifactId>

        dependency>

 

b.然后增加MYSQL依赖:

        <dependency>

            <groupId>mysqlgroupId>

            <artifactId>mysql-connector-javaartifactId>

        dependency>


c.Model类前增加标注@Entity

@Entity

public class user {


d.ID字段钱增加标注@Id @GeneratedValue

@Id

@GeneratedValue(strategy=GenerationType.AUTO)

private Integer id;


e.扩展数据仓库接口:

public interface UserRepository extends CrudRepository {}


f.在控制类前面增加标注

@Controller

@RequestMapping(path="/demo")

public class UserController {


g.在控制类仓库属性前面增加标注

@Autowired

private UserRepository repository;


h.在控制类操作函数之中和前面增加标注

@GetMapping(path = "/add")

public @ResponseBody String addNewUser(@RequestParam String name, @RequestParam String email) {

user u  = new user();

u.setName(name);

u.setEmail(email);

repository.save(u);

return "Saved";

}

 

    @Query("select id,username,sex,address from #{#entityName} u where u.username=:name")   

    List findUserModel(@Param("name") String username);

 

i.Application类前面增加标注

@SpringBootApplication

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class, args);

}

}

J.Application.properties中增加配置项

spring.jpa.hibernate.ddl-auto=create

spring.datasource.url=jdbc:mysql://localhost:3306/db_example

spring.datasource.username=springuser

spring.datasource.password=ThePassword


k.注解解说

@Entity说明此类是实体类,使用默认ORM规则,即class名即数据库表中表名,class字段名即表中的字段名如果想改变这种默认规则,就要使用@Table来改变class名与数据库中表名的映射规则,@Column来改变class中字段名与db中表的字段名的映射规则

@Query 这是JPA支持重量级查询方式有两种方式一种是JPQLSQL语言方式,一种是原生SQL的语言。常用情景如下:

***like表达式:

@Query(value = "select id,username,sex,address from UserModel b where b.name like %:name%")

List findByNameMatch(@Param("name") String name);

***原生SQL语言

@Query(value = "select * from user b where b.username=?1", nativeQuery = true)

List findByName(String name);

***使用@Param注解注入参数

@Query(value = "select id,username,sex,address from UserModel b where b.username = :name AND b.address=:address AND b.sex=:sex")

List findByNamedParam(@Param("name") String name, @Param("address") String address, @Param("sex") long sex);

***SPEL表达式

@Query(value = "select * from #{#entityName} b where b.name=?1", nativeQuery = true)
List findByName(String name);


l.JPA框架图

亲自动手搭建微服务框架和测试环境-7-JPA_第1张图片


m.JPQL语法

基本格式如下:

select 实体别名.属性名, 实体别名.属性名 from 实体名 as 实体别名 where 实体别名.实体属性 op 比较值


2 JPA查询方法和HQL查询语句对照

表达式

查询方法

hql查询语句

And

findByLastnameAndFirstname

… where x.lastname = ?1 and x.firstname = ?2

Or

findByLastnameOrFirstname

… where x.lastname = ?1 or x.firstname = ?2

Is,Equals

findByFirstname,findByFirstnameIs,findByFirstnameEqual

… where x.firstname = 1?

Between

findByStartDateBetween

… where x.startDate between 1? and ?2

LessThan

findByAgeLessThan

… where x.age < ?1

LessThanEqual

findByAgeLessThanEqual

… where x.age  ?1

GreaterThan

findByAgeGreaterThan

… where x.age > ?1

GreaterThanEqual

findByAgeGreaterThanEqual

… where x.age >= ?1

After

findByStartDateAfter

… where x.startDate > ?1

Before

findByStartDateBefore

… where x.startDate < ?1

IsNull

findByAgeIsNull

… where x.age is null

IsNotNull,NotNull

findByAge(Is)NotNull

… where x.age not null

Like

findByFirstnameLike

… where x.firstname like ?1

NotLike

findByFirstnameNotLike

… where x.firstname not like ?1

StartingWith

findByFirstnameStartingWith

… where x.firstname like ?1 (parameter bound with appended %)

EndingWith

findByFirstnameEndingWith

… where x.firstname like ?1 (parameter bound with prepended %)

Containing

findByFirstnameContaining

… where x.firstname like ?1 (parameter bound wrapped in %)

OrderBy

findByAgeOrderByLastnameDesc

… where x.age = ?1 order by x.lastname desc

Not

findByLastnameNot

… where x.lastname <> ?1

In

findByAgeIn(Collection ages)

… where x.age in ?1

NotIn

findByAgeNotIn(Collection age)

… where x.age not in ?1

True

findByActiveTrue()

… where x.active = true

False

findByActiveFalse()

… where x.active = false

IgnoreCase

findByFirstnameIgnoreCase

… where UPPER(x.firstame) = UPPER(?1)

 

3 MyBatisHibernate的区别

SpringBoot都支持mybatishibernate,实际上它们都属于ORM框架,整体架构也差不多,如下:

亲自动手搭建微服务框架和测试环境-7-JPA_第2张图片


亲自动手搭建微服务框架和测试环境-7-JPA_第3张图片


对比项

MyBatis

Hibernate

JDBC

支持

支持

JTA事务

支持

支持

SessionFactoryBuilder

支持

支持

SessionFactory

支持

支持

Session

支持

支持

开发难度

框架掌握简单

框架掌握复杂

SQL语句

支持原生SQL,便于性能优化

HQL,一般不需要编写原生SQL语句,性能较低

缓存

支持二级缓存,可能存在脏数据

支持二级缓存

可移植性

较差

较好

自动化

半自动

全自动

安全性

较差

较好

日志

较差

较好