java 带有Spring Boot 1.5的JPA
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 带有Spring Boot 1.5的JPA相关的知识,希望对你有一定的参考价值。
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "EFE_MESSAGES")
@Where(clause = "EMS_DATE_TIME > '01-JAN-2015'")
@GenericGenerator(name = "increment",strategy = "increment")
// Lombok method generators
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
// Ensures commencesOnDate is earlier than expiresAfterDate
// @MessageDateRange
@ScriptAssert(lang ="javascript", script ="_this.validateStartBeforeEnd()", message = "The start date must be at least one day before the expiry date")
public class Message {
/**
* The <code>EMS_NUMBER</code>column is used as the PK, and maintained using MAX+1 strategy -
* see the Hibernate-specific {@link GenericGenerator}<code>increment</code>annotation.
*/
@Id
@Builder.Default
@Column(name = "EMS_NUMBER")
@Setter(AccessLevel.PROTECTED)
@GeneratedValue(generator = "increment")
private Long id = null;
@CreatedDate
@Column(name = "EMS_DATE_TIME")
@DateTimeFormat(iso = ISO.DATE)
private LocalDate createdDate;
@CreatedBy
@Column(name ="EMS_ADDED_BY")
private String addedBy;
@Column(name ="EMS_TARGET_USER")
private String targetUser;
@DateTimeFormat(iso = ISO.DATE)
@Column(name = "EMS_COMMENCEMENT_DATE")
@NotNull(message = "The start date must be specified")
private LocalDate commencesOnDate;
@NotNull
@NonNull
@Column(name = "EMS_MESSAGE_TYPE")
@Enumerated(EnumType.STRING)
private MessageTypetype;
public boolean isNew() {
return getId() == null;
}
/**
* Used by the Hibernate-specific {@link ScriptAssert} annotation on this class.
*
* @return true if the commencement date is before the end date, or if either of the dates are
* null (null values preclude proper validation).
*/
public boolean validateStartBeforeEnd() {
// Ignore if either of the dates are null, as the validation can't be made
if (getCommencesOnDate() == null || getExpiresAfterDate() == null ) return true;
return getCommencesOnDate().isBefore(getExpiresAfterDate());
}
public boolean isCurrent() {
return getNullSafeExpiresAfterDate().isAfter(LocalDate.now()) && getNullSafeCommencesOnDate().isBefore(LocalDate.now().plusDays(1));
}
}
@Configuration
@PropertySource("classpath:jpa-${spring.profiles.active}.properties")
// Trigger Spring Data JPA goodness
@EnableJpaRepositories
// Enable auditing of who creates/updates an Entity and when
@EnableJpaAuditing
// For jsr310 java 8 java.time.*
// Configures the base packages used by auto-configuration when scanning for entity classes.
@EntityScan(basePackageClasses = { Message.class, Jsr310JpaConverters.class })
public class JpaConfig {
/**
* Bean for allowing the Jpa Auditing feature to access the authenticated user's username.
*/
@Bean
public AuditorAware<String> auditorProvider() {
return new SpringSecurityAuditorAware();
}
/**
* @return configuration for the {@link #appDataSource()} for the {@link Message} domain model.
* The properties come from <code>application.properties</code>.
*/
@Bean
@Primary
@ConfigurationProperties("datasource.app")
public DataSourceProperties appDataSourceProperties() {
return new DataSourceProperties();
}
@Primary
@Bean("dataSource")
@ConfigurationProperties("datasource.app")
public DataSource appDataSource() {
return appDataSourceProperties().initializeDataSourceBuilder().build();
}
/**
* @return configuration for the {@link #securityDataSource()} for the security infrastructure.
* The properties come from <code>application.properties</code>.
*/
@Bean
@ConfigurationProperties("datasource.security")
public DataSourceProperties securityDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@ConfigurationProperties("datasource.security")
public DataSource securityDataSource() {
return securityDataSourceProperties().initializeDataSourceBuilder().build();
}
}
import java.time.LocalDate;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import com.hansard.messaging.domain.Message;
import com.hansard.messaging.domain.QMessage;
import com.querydsl.core.types.dsl.BooleanExpression;
/**
* Spring Data JPA repository interface (no implementation required) for {@link Message}.
*
* <p>
* The {@link QueryDslPredicateExecutor} is used in conjunction with Maven artifact
* <code>com.querydsl.querydsl-jpa</code>. The corresponding {@link QMessage} class is generated to
* <code>target/generated-sources/java</code>.
*
* <p>
* A few DSL Expressions are implemented here for convenience. See {@link #isCurrent()} etc.
*
* @author Richard Cowin
*/
public interface MessageRepository extends JpaRepository<Message, Long>, QueryDslPredicateExecutor<Message> {
// Effectively "where UPPER(messageHtml) like '%UPPER(textToSearch)%'"
static BooleanExpression messageContains(String textToSearch) {
return QMessage.message.messageHtml.containsIgnoreCase(textToSearch);
}
static BooleanExpression isExpired() {
return QMessage.message.expiresAfterDate.loe(LocalDate.now());
}
static BooleanExpression isPending() {
return QMessage.message.commencesOnDate.after(LocalDate.now());
}
static BooleanExpression isCurrent() {
BooleanExpression beforeExpiry = QMessage.message.expiresAfterDate.after(LocalDate.now());
BooleanExpression afterCommencement = QMessage.message.commencesOnDate.loe(LocalDate.now());
return beforeExpiry.and(afterCommencement);
}
}
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.jpa.show-sql=true
datasource.app.type=org.apache.tomcat.jdbc.pool.DataSource
datasource.app.maximum-pool-size=8
datasource.app.url=jdbc:oracle:thin:@server:port:SID
datasource.app.username=username
datasource.app.password=passw0rd
<!-- Snippets only -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath />
</parent>
<properties>
<hibernate-validator.version>5.4.1.Final</hibernate-validator.version>
</properties>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
</dependency>
<build>
<plugin>
<!-- Remember to run mvn eclipse:eclipse, and mvn install -->
<!-- Generated sources need to be put on Eclipse's Build Path. -->
<!-- Also put querydsl-codegen jar file onto project's Java Compiler
| Annotation Processing | Factory Path. -->
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
</build>
@Controller
@RequestMapping("/messages")
// query and status are stored to help with searching
// message is stored for form handling
@SessionAttributes({ "query", "status", "message" })
public class MessageController {
@Autowired
private MessageService messageService;
@GetMapping("/")
public String searchMessages(@PageableDefault(sort = "createdDate", direction = Direction.DESC, size = 5) Pageable pageable,
@RequestParam(required = false) String query, @RequestParam(required = false) String status, ModelMap model) {
BooleanExpression searchExpr;
String statusSearch = getFromRequestOrModel(status, model, "status", "current");
switch (statusSearch) {
case "current":
searchExpr = MessageRepository.isCurrent();
break;
case "expired":
searchExpr = MessageRepository.isExpired();
break;
// Pending
default:
searchExpr = MessageRepository.isPending();
break;
}
String textSearch = getFromRequestOrModel(query, model, "query", "");
if (StringUtils.hasText(textSearch)) {
searchExpr = searchExpr.and(MessageRepository.messageContains(textSearch));
}
Page<Message> messages = messageService.findAll(searchExpr, pageable);
Order order = messages.getSort().iterator().next();
model.addAttribute("sort", order.getProperty() + "," + order.getDirection());
model.addAttribute("messages", messages);
return "messages";
}
}
以上是关于java 带有Spring Boot 1.5的JPA的主要内容,如果未能解决你的问题,请参考以下文章
使用 Spring Boot 1.5 在 oauth2 实现中返回错误凭据
干货|最新版 Spring Boot2.1.5 教程+案例合集
多模块 Gradle 项目 - 从 Spring-Boot 1.5 迁移到 2.1
从 Spring Boot 1.5 升级时为 Spring Boot 2.0 acuator 框架配置安全性
Spring Boot / Thymeleaf / Hibernate:带有 Java 注解的 Sessionfactory Bean