親自動手搭建微服務框架和測試環境-7-JPA

1 JPA使用步驟

JPA=Java Persistence APIJava持久層APIJDK5引入JPA ORM目的:簡化Java EE開發,整合ORM技術。JPA定義了JPQLJava Persistence Query Language)。java

Spring Data JPA默認集成的JPA ProviderHibernatemysql


a.pom.xml中增長JPA依賴spring

        <dependency>sql

            <groupId>org.springframework.boot</groupId>數據庫

            <artifactId>spring-boot-starter-data-jpa</artifactId>緩存

        </dependency>安全

 

b.而後增長MYSQL依賴:性能優化

        <dependency>mybatis

            <groupId>mysql</groupId>架構

            <artifactId>mysql-connector-java</artifactId>

        </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<user, Integer> {}


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<UserModel> 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<UserModel> findByNameMatch(@Param("name") String name);

***原生SQL語言

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

List<UserModel> 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<UserModel> 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<UserModel> findByName(String name);


l.JPA框架圖

image.png


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框架,總體架構也差很少,以下:

image.png


image.png


對比項

MyBatis

Hibernate

JDBC

支持

支持

JTA事務

支持

支持

SessionFactoryBuilder

支持

支持

SessionFactory

支持

支持

Session

支持

支持

開發難度

框架掌握簡單

框架掌握複雜

SQL語句

支持原生SQL,便於性能優化

HQL,通常不須要編寫原生SQL語句,性能較低

緩存

支持二級緩存,可能存在髒數據

支持二級緩存

可移植性

較差

較好

自動化

半自動

全自動

安全性

較差

較好

日誌

較差

較好

相關文章
相關標籤/搜索