说明:JPA到底是什么,我也没有很透彻的理解。先熟练应用再说。
照例,先上目录结构
细心的会发现,与上一篇相比,config等包都放进了com.cxs这个目录下了。之所以这么干,是为了重点体会一下application.javal里的@ComponentScan注解。application.java是SpringBoot的入口类,在这个类上加一个注解,SpringBoot就会自动取扫面这个路径下的包,碰到哪些标着@service、@controller、@entity的类就会把他们的bean注入到spring容器里。(如果对这段话不是很理解,建议按照第一篇的目录结构走,亲身错一波就大概知道是怎么回事了。不体验,无真相)。
下面上代码
一、引入依赖
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springboot</groupId>
<artifactId>springtest</artifactId>
<version>1.0-SNAPSHOT</version>
<!--引入parent-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<dependencies>
<!--SpringBoot必要依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--JPA-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--MySql连接-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
</dependencies>
</project>
二、src下的各个包
1、config包
Application.java
package com.cxs.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = "com.cxs")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
说明:这个是springBoot项目的入口。注意:@ComponentScan(basePackages = "com.cxs"),这是一个坑。自动扫描的这个包一定要包含住哪些含有@controller、@service的类,不然会报错。
JpaConfiguration.java
package com.cxs.config;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Created by Chenxs on 2019/06/28.
*/
@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@EnableJpaRepositories(basePackages = "com.cxs.repository")
@EntityScan(basePackages = "com.cxs.entity")
public class JpaConfiguration {
@Bean
PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor(){
return new PersistenceExceptionTranslationPostProcessor();
}
}
2、controller
UserController.java
package com.cxs.controller;
import com.cxs.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.cxs.service.UserService;
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/index")
@ResponseBody
public String Hello() {
return "hello";
}
@RequestMapping(value = "/show", method = RequestMethod.GET)
@ResponseBody
public String findUserByName(@RequestParam(value = "name") String name) {
User user= userService.findUserByName(name);
if (null != user)
return "ID:"+ user.getUserId() + "--------------------用户名:" + user.getUserName()+ "--------------------密码:" + user.getPassword();
else return "null";
}
}
说明:controller是与浏览器访问地址向关联的,可以看成负责跳转的。
3.entity
User.java
package com.cxs.entity;
import javax.persistence.*;
@Entity
@Table(name = "tbl_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long userId;
private String userName;
private String password;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
说明:这是一个和数据库表相对应的类。
4.respository
package com.cxs.repository;
import com.cxs.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User,Integer> {
@Query("select t from User t where t.userName = :userName")
User findByUserName(@Param("userName") String userName);
}
说明:这个类用来操作上一个类的对象。
5.service
UserService.java
package com.cxs.service;
import com.cxs.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cxs.repository.UserRepository;
/**
* Created by Song on 2017/2/15.
* User业务逻辑
*/
@Service
public class UserService {
@Autowired
private UserRepository userRepositoty;
public User findUserByName(String name){
User user = null;
try{
user = userRepositoty.findByUserName(name);
}catch (Exception e){}
return user;
}
}
说明:这一块是处理业务逻辑的
三、application.properties
#命名空间
server.context-path=/demo
#端口号
server.port=8090
#MySQL
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/cx?characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
#Spring Data JPA
spring.jpa.database=MYSQL
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
四、访问