spring boot(二)spring data jpa以及事物配置

时间:2021-12-28 16:28:44

本章目的:使用spring data jpa连接mysql,实现增删改查和事物的配置。

  • pom.xml引入jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
  • application.properties配置数据源
server.port=20001
spring.datasource.url=jdbc:mysql://localhost:3307/crawler
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
  • 创建实体类User
@Entity
public class User {
private Long id;
private String name;
private Integer age;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

@Column(nullable = false)
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Column(nullable = false)
public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

}
  • 创建UserRepository
public interface UserRepository extends JpaRepository<User, Long> {
User findByName(String name);

User findByAgeGreaterThan(Integer age);

List<User> findByNameLike(String name);

}
  • 创建UserService
@Service
public class UserService {
@Autowired
private UserRepository userRepository;

public User findUser(String name) {
return userRepository.findByName(name);
}

public List<User> findList() {
return userRepository.findAll();
}

public Long save(User user) {
return userRepository.save(user).getId();
}

public void saveListUser(List<User> list) {
for (User user : list)
save(user);
}

}
  • 创建API
@RestController
@RequestMapping("/user")
public class UserWeb {
@Autowired
private UserService userService;

@RequestMapping("/find")
public String findUser(String name) throws Exception {
return userService.findUser(name).getName();
}

@RequestMapping("list")
public String list() throws JSONException {
JSONObject out = new JSONObject();
out.put("list", userService.findList());
return out.toString();
}

@RequestMapping("/save")
public String save(String name, Integer age) {
User user = new User();
user.setName(name);
user.setAge(age);
Long id = userService.save(user);
return id.toString();
}

@RequestMapping("/saveList")
public String saveList(String name, Integer age) {
List<User> list = new ArrayList<User>();
for (int i = 6; i < 11; i++) {
User user = new User();
user.setName(name + "_0000" + i);
user.setAge(age);
list.add(user);
}
userService.saveListUser(list);
return "OK";
}
}

启动主程序,访问http://localhost:20001/list获取user列表

  • 事物
    springboot中的事物非常简单,只需要两步

  • 主程序中加入注解@EnableTransactionManagement

  • service方法中加入注解@Transactional