与springboot_SSM的创建区别在于:添加JPA,相当于添加hibernate的组件
UserController
package net.wanho.controller;
import com.alibaba.fastjson.JSONObject;
import net.wanho.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@RequestMapping("/add")
public String addUser()
{
userService.addUser();
return "success";
}
@RequestMapping("/query")
public JSONObject queryUser()
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("status",200);
jsonObject.put("users",userService.queryUser());
return jsonObject;
}
}
UserDao
package net.wanho.dao;
import net.wanho.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserDao extends JpaRepository<User , Integer> {
}
User
package net.wanho.entity;
import javax.persistence.*;
@Entity
@Table(name = "tt_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "name")
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User() {
}
public User(int id,String name)
{
this.id = id;
this.name = name;
}
}
UserService
package net.wanho.service;
import net.wanho.dao.UserDao;
import net.wanho.entity.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserService {
@Resource
private UserDao userDao;
@Transactional
public void addUser() {
User user = new User();
user.setName("boot");
// ssh操作数据库的方法不在dao层里,用的全自动自带方法
userDao.save(user);
System.out.println(1/0);
}
public List<User> queryUser()
{
return userDao.findAll();
}
}
SpringbootDemoApplication
package net.wanho;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableTransactionManagement
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
application.yml
server :
port : 8088
spring :
datasource:
driver-class-name : com.mysql.jdbc.Driver
url : jdbc:mysql://localhost:3306/test?characterEncoding=utf8
username : root
password : root
#Spring Data JPA
jpa:
database : mysql
show-sql : true
hibernate.ddl-auto : create
hibernate.dialect : org.hibernate.dialect.MySQL5Dialect