利用JpaRepository实现增删改查
pom.xml:
<!-- web支持 -->
<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>
<scope>runtime</scope>
</dependency>
application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=1234
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql=true
Entity:
package com.crisy.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@Column
private String name;
@Column
private Long department;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getDepartment() {
return department;
}
public void setDepartment(Long department) {
this.department = department;
}
}
Dao层:
package com.crisy.service;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.crisy.entity.Employee;
@Transactional
public interface EmployeeService extends JpaRepository<Employee, Long>{
//根据方法名来自动的生成SQL
Employee findById(Long id);
//修改 一定要加@Transactional和 @Modifying
@Modifying
@Query(value = "update employee set name = :name where id = :id",nativeQuery = true)
void updateNameById(@Param("id") Long id, @Param("name") String name);
}
Controller:
package com.crisy.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.crisy.entity.Employee;
import com.crisy.service.EmployeeService;
/**
* 测试jpa
* Title:EmployeeController
* Description:
* @author wangchenxin
* @date 2018-7-27 上午9:00:11
*/
@RestController
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
//根据ID加载实体类
@RequestMapping(value="/getEmp")
public Employee loadEmployee(){
Employee e = employeeService.findById(1l);
return e;
}
//保存
@RequestMapping(value="/addEmp")
public void add(){
Employee e = new Employee();
e.setDepartment(1l);
e.setName("曹操");
employeeService.save(e);
}
//删除
@RequestMapping(value="/deleteEmp")
public void delete(){
employeeService.delete(1l);
}
//更新
@RequestMapping(value="/updateEmp")
public void update(){
employeeService.updateNameById(3l,"猪八戒");
}
}
启动类:
package com.crisy.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@ComponentScan(basePackages = {"com.crisy.*"})
@EnableJpaRepositories(basePackages="com.crisy.*")
@EntityScan(basePackages="com.crisy.*")
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
自定义Filter
package com.crisy.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
/**
* 自定义filter
* 实现Filter接口,实现Filter方法
* Title:MyFilter
* Description:
* @author wangchenxin
* @date 2018-7-26 下午5:13:03
*/
public class MyFilter implements Filter {
public void destroy() {
System.out.println("destroy");
}
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) arg0;
System.out.println("this is MyFilter,url:" + request.getRequestURI());
filterChain.doFilter(arg0, arg1);
}
public void init(FilterConfig arg0) throws ServletException {
System.out.println("init");
}
}
package com.crisy.filter;
import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 添加@Configuration 注解,将自定义Filter加入过滤链
* Title:WebConfiguration
* Description:
* @author wangchenxin
* @date 2018-7-26 下午5:12:55
*/
@Configuration
public class WebConfiguration {
@Bean
public RemoteIpFilter remoteIpFilter() {
return new RemoteIpFilter();
}
@Bean
public FilterRegistrationBean testFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new MyFilter());
registration.addUrlPatterns("/*");
registration.addInitParameter("paramName", "paramValue");
registration.setName("MyFilter");
registration.setOrder(1);
return registration;
}
}
遇到的问题:
1、public interface EmployeeService extends JpaRepository<Employee, Long> 定义错误
JpaRepository是一个接口,需要定义一个接口去继承
2、Consider defining a bean of type 'com.crisy.service.EmployeeService' in your configuration.找不到service
解决办法:在启动类添加注解@EnableJpaRepositories(basePackages="com.crisy.*")
Error creating bean with name 'employeeController': Unsatisfied dependency expressed through field 'employeeService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeService': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.crisy.entity.Employee 找不到Entity
解决办法:在启动类添加注解@EntityScan(basePackages="com.crisy.*")
3、java.sql.SQLException: Can not issue data manipulation statements with executeQuery(). could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet
解决办法:service类@Transactional,更新方法添加@Modifying
步骤总结:
1、在pom.xml中添加相应jar包:Web,JPA,MySQL
2、添加数据库配置文件
3、添加实体类,类需要添加@Entity注解,类的属性上面需要添加@Id或者@Column注解,不映射成列的字段需要加@Transient注解
4、Dao接口需要实现JpaRepository接口,默认有增删查方法,修改方法可以自己定义,可以根据方法名来自动的生产SQL。需要进行修改的时候,类需要添加@Transactional注解,方法添加@Modifying注解
5、Controller需要添加@Controller注解,并使用@Autowired装配Dao接口
6、启动类注意
@ComponentScan(basePackages = {"com.crisy.*"})
@EnableJpaRepositories(basePackages="com.crisy.*")
@EntityScan(basePackages="com.crisy.*")
注解:
@Entity:表示这是一个实体
@Table:指定Entity所要映射的数据库表,指定表名称,如果不指定,就是类名的首字母小写
@Id:对应数据库中的ID,主键
@Column:对应数据库表中普通属性
@GeneratedValue:指定主键的生成策略,根据不同的数据库自动选择
@EnableJpaRepositories(basePackages="com.crisy.*"):扫描指定的包下的Respository
@EntityScan(basePackages="com.crisy.*") :扫描指定包下的实体
@ComponentScan(basePackages="com.crisy.*"):指定扫描的包,否则只扫描此类所在的包
@Modifying:完成修改操作(不包括新增)
@Transactional:事务注解