您的位置:首页 > 编程语言 > Java开发

关于Spring boot中JPA的基本框架构造

2020-02-12 01:22 225 查看

最近在学习Spring boot中JPA的配置,对于其一些基本框架构造有了个大概的认识
首先整个构造分为四个大部分

分为controller层,dao层,entity层以及service层。
实体类写在entity层中。

首先配置application.yml文件 (使用application.properties配置也是可以的)

server:
port: 8887

#数据库配置
spring:
datasource:
username: 在这里写数据库的名称
password: 这里写数据库的密码
driver-class-name: com.mysql.cj.jdbc.Driver
url:      jdbc:在这里写自己数据库的链接
jpa:
hibernate:
ddl-auto: update
show-sql: true

# formatSQL得这样写
properties:
hibernate:
format_sql: true

spring:
thymeleaf:
prefix=classpath:/templates/:

在controller中

@Controller
public class BookController2 {

@Autowired
private UserService userService;

@GetMapping("/books")
public ModelAndView books(){

System.out.println("我进来了!");

User user=new User();
user.setId(33);
user.setName("test");
user.setCreateTime("2019");
System.out.println("创建一个新的User信息");

int a=userService.addUser(user);
System.out.println("成功过"+a);
}
}

在dao层中写一个接口

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {

}

而在entity中写一个实体类

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

//部门
@Column
private String name;
//创建时间
private String createTime;

//部门ID
Integer departmentId ;

public User() {
//JPA必须要有一个空的构造函数
}

public Integer getId() {
return id;
}

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

public String getName() {
return name;
}

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

public String getCreateTime() {
return createTime;
}

public void setCreateTime(String createTime) {
this.createTime = createTime;
}
}

而在service中 则是需要这么建立


其中User Service只是一个接口 具体的业务逻辑则是在UserServicelmpl中实现的

@Service
@Transactional
public class UserServiceImpl implements UserService {

@Autowired
UserRepository userDao;

@Override
public Integer addUser(User user){
//添加user
userDao.save(user);
//取到相关id
Integer id = user.getId();
user.setName("1"+user.getName());
//更新user
userDao.save(user);

return id;
}
}

通过8887端口对其进行访问之后会在控制台显示

显示我进来了 说明运行成功 之前输入的数值也被成功输出

  • 点赞
  • 收藏
  • 分享
  • 文章举报
干了这杯孤独 发布了1 篇原创文章 · 获赞 0 · 访问量 4 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: