3. Processing data-Spring Combat 5th Edition


This chapter includes:

  • Use spring's JdbcTemplate;
  • Use SimpleJdbcTemplate to insert data;
  • Declare JPA repositories with spring data.

2. Spring Data

The Spring Data project includes the following projects:

  • spring data JPA, this is for relational database;
  • spring data MongoDB, this is for Mongo document database;
  • spring data Neo4j, this is for Neo4j graph database;
  • spring data Cassandra, this is for Cassandra database.

2.1 Add spring data JPA to the project

Add the following dependencies:

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-jpa</artifactId>
	</dependency>

The default is Hibernate. If you need to change to other implementations, you can do the following:

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-jpa</artifactId>
		<exclusions>
			<exclusion>
				<artifactId>hibernate-entitymanager</artifactId>
				<groupId>org.hibernate</groupId>
			</exclusion>
		</exclusions>
	</dependency>
	<dependency>
		<groupId>org.eclipse.persistence</groupId>
		<artifactId>eclipselink</artifactId>
		<version>2.5.2</version>
	</dependency>

2.2 Statement of entities

package tacos;
import javax.persistence.Entity;
import javax.persistence.Id;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;

@Data
@RequiredArgsConstructor
@NoArgsConstructor(access=AccessLevel.PRIVATE, force=true)
@Entity
public class Ingredient {
  
  @Id
  private final String id;
  private final String name;
  private final Type type;
  
  public static enum Type {
    WRAP, PROTEIN, VEGGIES, CHEESE, SAUCE
  }

}

Add @Entity and @Id.
Annotation @NoArgsConstructor, JPA requires a parameterless constructor, because it does not want to use the secondary method, so set to private.

2.3 Declare JPA repositories

Just inherit CrudRepository.

package tacos.data;

import org.springframework.data.repository.CrudRepository;

import tacos.Ingredient;

public interface IngredientRepository extends CrudRepository<Ingredient, String> {

}

2.4 Custom JPA repositories

example:

List<Order> findByDeliveryZip(String deliveryZip);

Spring Data uses a domain-specific language (DSL) mechanism to resolve method signatures.

List<Order> readOrdersByDeliveryZipAndPlacedAtBetween(
String deliveryZip, Date startDate, Date endDate);

Insert picture description here
There are also the following examples:
Insert picture description here
Insert picture description here
complex can use @Query:

@Query("Order o where o.deliveryCity='Seattle'")
List<Order> readOrdersDeliveredInSeattle();
Published 97 original articles · praised 3 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_39530821/article/details/103788788