8. (C) CASAREAL, Inc. All rights reserved.
8
Spring Web 4 Spring MVC
Spring Boot
Developer
2 Spring Boot
Spring Cloud
Services
3
Spring Cloud Microservices
17. (C) CASAREAL, Inc. All rights reserved.
▸
17
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
18. (C) CASAREAL, Inc. All rights reserved.
▸
18
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.12.Final</version>
</dependency>
19. (C) CASAREAL, Inc. All rights reserved.
▸
19
logging.level.org.hibernate.SQL=debug
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=
trace
<logger name="org.hibernate.SQL" level="DEBUG" />
<logger name="org.hibernate.type.descriptor.sql.BasicBinder"
level="TRACE" />
▸
▸
※hibernate.show_sql=true
20. (C) CASAREAL, Inc. All rights reserved.
▸
20
spring.jpa.properties.hibernate.format_sql=true
▸
▸
▸
27. (C) CASAREAL, Inc. All rights reserved.
27
NEW new
MANAGED
DETACHED
REMOVED
28. (C) CASAREAL, Inc. All rights reserved.
28
find()
persist() 1
remove() 1
merge()
detach()
flush() DB
clear()
refresh() DB
29. (C) CASAREAL, Inc. All rights reserved.
29
persist()
detach()
clear()
merge()
remove()
flush()
flush()
refresh()
find()
JPQL
detach()
clear()
30. (C) CASAREAL, Inc. All rights reserved.
30
EntityManager em = …;
// 1 2
Product product = em.find(Product.class, 1);
▸
select
product0_.id as id1_5_0_,
product0_.category_id as category4_5_0_,
product0_.name as name2_5_0_,
product0_.price as price3_5_0_,
product0_.vendor_id as vendor_i5_5_0_
from
product product0_
where
product0_.id=?
SQL
31. (C) CASAREAL, Inc. All rights reserved.
31
Product product = new Product(“ ”, 100000L);
em.persist(product);
▸
▸
insert
into
product
(category_id, name, price, vendor_id, id)
values
(?, ?, ?, ?, ?)
32. (C) CASAREAL, Inc. All rights reserved.
32
// find() MANAGED
Product product = em.find(Product.class, 1);
//
product.setName(" ");
// ( OK)
em.flush();
▸
33. (C) CASAREAL, Inc. All rights reserved.
33
select … from product product0_ where product0_.id=?
binding parameter [1] as [INTEGER] - [1]
update product
set category_id=?, name=?, price=?, vendor_id=?
where id=?
binding parameter [1] as [INTEGER] - [1]
binding parameter [2] as [VARCHAR] - [ ]
binding parameter [3] as [BIGINT] - [100000]
binding parameter [4] as [INTEGER] - [1]
binding parameter [5] as [INTEGER] - [1]
34. (C) CASAREAL, Inc. All rights reserved.
34
Product product = new Product();
product.setId(1);
product.setName(“ ");
// merge()
em.merge(product);
em.flush();
▸
35. (C) CASAREAL, Inc. All rights reserved.
35
select … from product product0_ where product0_.id=?
binding parameter [1] as [INTEGER] - [1]
update product
set category_id=?, name=?, price=?, vendor_id=?
where id=?
binding parameter [1] as [INTEGER] - [null]
binding parameter [2] as [VARCHAR] - [ ]
binding parameter [3] as [BIGINT] - [null]
binding parameter [4] as [INTEGER] - [null]
binding parameter [5] as [INTEGER] - [1]
▸
36. (C) CASAREAL, Inc. All rights reserved.
▸
▸
36
Product mergedProduct = em.merge(product);
// MANAGED
assertTrue(em.contains(mergedProduct));
//
assertFalse(em.contains(product));
37. (C) CASAREAL, Inc. All rights reserved.
37
// find() MANAGED
Product product = em.find(Product.class, 30);
// REMOVED
em.remove(product);
// ( OK)
em.flush();
▸
38. (C) CASAREAL, Inc. All rights reserved.
38
select … from product product0_ where product0_.id=?
binding parameter [1] as [INTEGER] - [30]
delete from product where id=?
binding parameter [1] as [INTEGER] - [30]
39. (C) CASAREAL, Inc. All rights reserved.
39
// find() MANAGED
Product product = em.find(Product.class, 30);
// REMOVED
em.remove(product);
// DETACHED
em.detach(product);
// DETACHED DB
em.flush();
▸
43. (C) CASAREAL, Inc. All rights reserved.
43
TypedQuery<Product> query = em.createQuery(
"SELECT p FROM Product p WHERE p.id = :id",
Product.class);
query.setParameter("id", 1);
Product product = query.getSingleResult();
TypedQuery<Product> query = em.createQuery(
"SELECT p FROM Product p WHERE p.id <= :maxId"
+ " ORDER BY p.id", Product.class);
query.setParameter("maxId", 5);
List<Product> list = query.getResultList();
▸
▸
44. (C) CASAREAL, Inc. All rights reserved.
44
select
product0_.id as id1_5_,
product0_.category_id as category4_5_,
product0_.name as name2_5_,
product0_.price as price3_5_,
product0_.vendor_id as vendor_i5_5_
from
product product0_
where
product0_.id=?
▸
45. (C) CASAREAL, Inc. All rights reserved.
45
SELECT FROM [AS]
WHERE . <= :
▸
▸
▸
46. (C) CASAREAL, Inc. All rights reserved.
▸
▸
46
SELECT new com.example.demo.dto.CountDto(
od.product.id, COUNT(od))
FROM OrderDetail od GROUP BY od.product.id
52. (C) CASAREAL, Inc. All rights reserved.
▸
▸
▸
▸
52
@Entity
public class Product {
…
@ManyToOne
@JoinColumn(name="vendor_id")
private Vendor vendor;
}
@Entity
public class Vendor {
…
}
54. (C) CASAREAL, Inc. All rights reserved.
▸
▸
▸
54
@Entity
public class Product {
…
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="vendor_id")
private Vendor vendor;
}
55. (C) CASAREAL, Inc. All rights reserved.
55
select ( ) from product product0_
where product0_.id=?
select ( ) from vendor vendor0_
where vendor0_.id=?
@Entity public class Product {
@ManyToOne(fetch = FetchType.LAZY)
private Vendor vendor;
}
Product p = em.find(Product.class, 1);
Vendor v = p.getVendor();
String n = v.getName() // SELECT
2
SELECT
56. (C) CASAREAL, Inc. All rights reserved.
▸
56
em.getTransaction().begin();
Product p = em.find(Product.class, 1);
em.getTransaction().rollback();
Vendor v = p.getVendor();
String n = v.getName(); //
57. (C) CASAREAL, Inc. All rights reserved.
57
@Entity public class Product {
@ManyToOne(fetch = FetchType.EAGER)
private Vendor vendor;
}
Product p = em.find(Product.class, 1);
Vendor v = p.getVendor(); //
select ( ) from product product0_
left outer join vendor vendor2_
on product0_.vendor_id=vendor2_.id
where product0_.id=?
1
SELECT
59. (C) CASAREAL, Inc. All rights reserved.
59
// order_summary SELECT 1
List<OrderSummary> list = em.createQuery(
"SELECT os FROM OrderSummary os",OrderSummary.class)
.getResultList();
for (OrderSummary os : list) {
// order_detail
System.out.println(os);
for (OrderDetail od : os.getOrderDetailList()) {
// order_detail SELECT (N )
System.out.println(od);
}
}
60. (C) CASAREAL, Inc. All rights reserved.
60
// order_summary SELECT 1
List<OrderSummary> list = em.createQuery(
"SELECT os FROM OrderSummary os" +
" JOIN os.orderDetailList", OrderSummary.class)
.getResultList();
for (OrderSummary os : list) {
// order_detail
System.out.println(os);
for (OrderDetail od : os.getOrderDetailList()) {
// order_detail SELECT (N )
System.out.println(od);
}
}
61. (C) CASAREAL, Inc. All rights reserved.
61
select
ordersumma0_.id as id1_3_,
ordersumma0_.customer_id as customer3_3_,
ordersumma0_.order_timestamp as order_ti2_3_
from
order_summary ordersumma0_
inner join
order_detail orderdetai1_
on ordersumma0_.id=orderdetai1_.summary_id
where
ordersumma0_.id=?
JOIN
order_summary
62. (C) CASAREAL, Inc. All rights reserved.
▸
62
// order_summary SELECT 1
List<OrderSummary> list = em.createQuery(
"SELECT os FROM OrderSummary os" +
" JOIN FETCH os.orderDetailList" +
, OrderSummary.class)
.getResultList();
63. (C) CASAREAL, Inc. All rights reserved.
63
select
ordersumma0_.id as id1_3_0_,
orderdetai1_.id as id1_2_1_,
ordersumma0_.customer_id as customer3_3_0_,
ordersumma0_.order_timestamp as order_ti2_3_0_,
orderdetai1_.amount as amount2_2_1_,
orderdetai1_.product_id as product_3_2_1_,
orderdetai1_.summary_id as summary_4_2_0__,
orderdetai1_.id as id1_2_0__
from
order_summary ordersumma0_
inner join
order_detail orderdetai1_
on ordersumma0_.id=orderdetai1_.summary_id
where
ordersumma0_.id=?
JOIN
65. (C) CASAREAL, Inc. All rights reserved.
65
// order_summary SELECT 1
List<OrderSummary> list = em.createQuery(
"SELECT DISTINCT os FROM OrderSummary os" +
" JOIN FETCH os.orderDetailList" +
, OrderSummary.class)
.getResultList();
66. (C) CASAREAL, Inc. All rights reserved.
66
select distinct
ordersumma0_.id as id1_3_0_,
orderdetai1_.id as id1_2_1_,
ordersumma0_.customer_id as customer3_3_0_,
ordersumma0_.order_timestamp as order_ti2_3_0_,
orderdetai1_.amount as amount2_2_1_,
orderdetai1_.product_id as product_3_2_1_,
orderdetai1_.summary_id as summary_4_2_0__,
orderdetai1_.id as id1_2_0__
from
order_summary ordersumma0_
inner join
order_detail orderdetai1_
on ordersumma0_.id=orderdetai1_.summary_id
where
ordersumma0_.id=?
distinct
SQL
69. (C) CASAREAL, Inc. All rights reserved.
// order_summary order_detail product JOIN
OrderSummary orderSummary = em.createQuery(
"SELECT os FROM OrderSummary os" +
" JOIN FETCH os.orderDetailList od" +
" JOIN FETCH od.product p" +
" WHERE os.id = :id", OrderSummary.class)
.setParameter("id", 1)
.getSingleResult();
▸
69
70. (C) CASAREAL, Inc. All rights reserved.
70
select
ordersumma0_.id as id1_3_0_,
orderdetai1_.id as id1_2_1_,
product2_.id as id1_4_2_,
ordersumma0_.customer_id as customer3_3_0_,
ordersumma0_.order_timestamp as order_ti2_3_0_,
orderdetai1_.amount as amount2_2_1_,
orderdetai1_.product_id as product_3_2_1_,
orderdetai1_.summary_id as summary_4_2_0__,
orderdetai1_.id as id1_2_0__,
product2_.category_id as category4_4_2_,
product2_.name as name2_4_2_,
product2_.price as price3_4_2_,
product2_.vendor_id as vendor_i5_4_2_
from
order_summary ordersumma0_
inner join
order_detail orderdetai1_
on ordersumma0_.id=orderdetai1_.summary_id
inner join
product product2_
on orderdetai1_.product_id=product2_.id
where
ordersumma0_.id=?
3
JOIN
76. (C) CASAREAL, Inc. All rights reserved.
▸
▸
▸
76
Query query = em.createNativeQuery(
"select id, name, price, vendor_id"
+ " from product where id = :id", Product.class);
query.setParameter("id", 1);
Product product = (Product) query.getSingleResult();
77. (C) CASAREAL, Inc. All rights reserved.
▸
77
Query query = em.createNativeQuery(
"select id, name from product where id = :id");
query.setParameter("id", 1);
// 0 id 1 name
Object[] objs = (Object[]) query.getSingleResult();
Integer productId = (Integer) objs[0];
String productName = (String) objs[1];
79. (C) CASAREAL, Inc. All rights reserved.
79
@Entity
@SqlResultSetMapping(
name = "product_id_name", //
classes = {
@ConstructorResult(targetClass = ProductDto.class,
columns = {
@ColumnResult(name = "id"),
@ColumnResult(name = "name")
}
)
}
)
public class Product { … }
※@SqlResultSetMappings @SqlResultSetMapping
80. (C) CASAREAL, Inc. All rights reserved.
80
Query query = em.createNativeQuery(
"select id, name from product where id = :id",
"product_id_name"); // @SqlResultSetMapping name
query.setParameter("id", 1);
ProductDto productDto =
(ProductDto) query.getSingleResult();
public class ProductDto {
private Integer id;
private String name;
public ProductDto(Integer id, String name) { … }
}
81. (C) CASAREAL, Inc. All rights reserved.
▸
81
// H2 Database LEFT
TypedQuery<Product> query = em.createQuery(
"SELECT p FROM Product p"
+ " WHERE FUNCTION('LEFT', p.name, 2) = ' '",
Product.class);
List<Product> productList = query.getResultList();
82. (C) CASAREAL, Inc. All rights reserved.
▸
82
StoredProcedureQuery query =
em.createStoredProcedureQuery(" ",
.class);
query.setParameter(" ", );
List< > list =
(List< >) query.getResultList();
※
83. (C) CASAREAL, Inc. All rights reserved.
▸
83
@Entity
@Index(members = {"name"})
public class Product {
…
}
※
※@Indices @Index
91. (C) CASAREAL, Inc. All rights reserved.
91
@Service
public class ProductService {
private final ProductRepository repo;
@Autowired // DI
public ProductService(ProductRepository repo) {
this.repo = repo;
}
@Transactional
public void insert(Product product) {
repo.save(product);
}
}
※@Autowired Spring 4.3
1
92. (C) CASAREAL, Inc. All rights reserved.
▸
▸
92
public interface ProductRepository
extends JpaRepository<Product, Integer> {
@Query("SELECT p FROM Product p JOIN FETCH p.vendor"
+ " WHERE p.id = :id")
Product findByIdJoinFetch(@Param("id") Integer id);
}
93. (C) CASAREAL, Inc. All rights reserved.
▸
93
public interface ProductRepository
extends JpaRepository<Product, Integer> {
@Modifying
@Query("UPDATE Product p SET p.name = :name"
+ " WHERE p.id = :id")
void updateName(@Param("name") String name,
@Param("id") Integer id);
}
94. (C) CASAREAL, Inc. All rights reserved.
▸
94
public interface ProductRepository
extends JpaRepository<Product, Integer> {
@Lock(LockModeType.PESSIMISTIC_READ)
@Query("SELECT p FROM Product p JOIN FETCH p.vendor"
+ " WHERE p.id = :id")
Product findByIdJoinFetch(@Param("id") Integer id);
}
※
https://www.slideshare.net/masatoshitada7/jpa20140518-ccc-r15-jjug-ccc
95. (C) CASAREAL, Inc. All rights reserved.
▸
95
public interface ProductRepository
extends JpaRepository<Product, Integer> {
@EntityGraph(" ")
@Query("SELECT p FROM Product p JOIN FETCH p.vendor"
+ " WHERE p.id = :id")
Product findByIdJoinFetch(@Param("id") Integer id);
}
※
https://blog.ik.am/entries/350
96. (C) CASAREAL, Inc. All rights reserved.
▸
96
public interface ProductRepository
extends JpaRepository<Product, Integer> {
// name
List<Product> findByNameContaining(String keyword);
}
97. (C) CASAREAL, Inc. All rights reserved.
97
select
product0_.id as id1_4_,
product0_.category_id as category4_4_,
product0_.name as name2_4_,
product0_.price as price3_4_,
product0_.vendor_id as vendor_i5_4_
from
product product0_
where
product0_.name like ?
binding parameter [1] as [VARCHAR] - [% %]
100. (C) CASAREAL, Inc. All rights reserved.
▸
100
@Entity public class Hoge {
@CreatedBy String createdUser;
@CreatedDate LocalDateTime createdDate;
@LastModifiedBy String modifiedUser;
@LastModifiedDate LocalDateTime lastModifiedDate;
}
101. (C) CASAREAL, Inc. All rights reserved.
101
@SpringBootApplication
@EnableJpaAuditing(auditorAwareRef = "myAuditorAware")
public class SpringDataJpaDaitokaiApplication { … }
@Component
public class MyAuditorAware
implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
return Optional.of("user01");}
}
Spring Security
OK
102. (C) CASAREAL, Inc. All rights reserved.
102
<entity-mappings>
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener
class="org.springframework.data.jpa.domain.support.AuditingEntityListene
r" />
</entity-listeners>
</persistence-unit-defaults>
</persistence-unit-metadata>
</entity-mappings>
▸
▸
107. (C) CASAREAL, Inc. All rights reserved.
▸
107
http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#boot-features-jpa-in-
web-environment
108. (C) CASAREAL, Inc. All rights reserved.
▸
108
spring.jpa.open-in-view=false
109. (C) CASAREAL, Inc. All rights reserved.
▸
▸
109
@Entity public class Hoge {
// Spring Boot @Column
@Column(name=“foo_bar”) String fooBar;
}
http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#howto-configure-
hibernate-naming-strategy
110. (C) CASAREAL, Inc. All rights reserved.
▸
110
spring.jpa.hibernate.naming.physical-strategy=Strategy FQCN
spring.jpa.hibernate.naming.implicit-strategy=Strategy FQCN
111. (C) CASAREAL, Inc. All rights reserved.
▸
▸
111
@SpringBootApplication
@EntityScan(basePackages = {
"com.example.demo.persistence.entity",
"org.springframework.data.jpa.convert.threeten"})
public class SpringDataJpaDaitokaiApplication { … }
http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#howto-separate-entity-
definitions-from-spring-configuration