Spring Boot之使用thymeleaf和jpa增删改查简单实例

这篇文章介绍如何使用jpa和thymeleaf做一个增删改查的示例。

配置文件

pom包配置

pom包里面添加jpa和thymeleaf的相关包引用

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

在application.properties中添加配置

spring.datasource.url = jdbc:mysql://localhost:3309/springboot?useSSL\=false&characterEncoding\=UTF-8&autoReconnect\=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#启动时会根据实体类生成数据表,或者更新表结构,不清空数据,开发阶段使用;validate:表结构稳定后使用,可用于正式环境;
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
# 控制台打印sql
spring.jpa.show-sql= true

spring.thymeleaf.cache=false

其中propertiesspring.thymeleaf.cache=false是关闭thymeleaf的缓存,不然在开发过程中修改页面不会立刻生效需要重启,生产可配置为true。

在项目resources目录下会有两个文件夹:static目录用于放置网站的静态内容如css、js、图片;templates目录用于放置项目使用的页面模板。

启动类

启动类需要添加Servlet的支持

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

@SpringBootApplication
//若打包成war包,则需要继承SpringBootServletInitializer类,覆盖其configure(SpringApplicationBuilder)方法
public class JpaThymeleafApplication extends SpringBootServletInitializer {
	
	//添加servlet依赖
	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application){
		return application.sources(JpaThymeleafApplication.class);
	}
	
	public static void main(String[] args) {
		SpringApplication.run(JpaThymeleafApplication.class, args);
	}

}

数据库层代码

实体类映射数据库表

@Entity
@Table(name="user")
public class UserDo {
	@Id @GeneratedValue
	private Integer id;
	private String name;
	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;
	}
		
}

继承JpaRepository类会自动实现很多内置的方法,包括增删改查。也可以根据方法名来自动生成相关sql

public interface UserRepository extends JpaRepository<UserDo, Integer> {
	UserDo findById(Integer id);
	
	Integer deleteById(Integer id);
}

 

业务层处理

service调用jpa实现相关的增删改查,实际项目中service层处理具体的业务代码。

@Service
public class UserService {
	@Resource 
	private UserRepository userRepository;
	
	
	public List<UserDo> getUserList(){
		return userRepository.findAll();
	}
	
	public UserDo findUserById(Integer id){
		return userRepository.findById(id);
	}
	
	@Transactional
	public UserDo saveUser(UserDo user){
		return userRepository.save(user);
	}
	
	@Transactional
	public UserDo editUser(UserDo user){
		return userRepository.save(user);
	}
	
	@Transactional
	public Integer deleteUser(Integer id){
		return userRepository.deleteById(id);
	}
}

 注意,需要事务处理的方法需要注解@Transactional,否则后面调用时可能会出现报错。

Controller负责接收请求,处理完后将页面内容返回给前端。

@Controller
public class UserController {
	
	@Resource
	private UserService userService;
	
	@RequestMapping("/")
	public String index() {
		return "redirect:/list";//页面重定向到list
	}
	
	@RequestMapping("/list")
	public String list(Model model){
		List<UserDo> userList = userService.getUserList();
		model.addAttribute("userList", userList);
		return "user/list";//代表会直接去resources目录下找相关的文件
	}
	
	@RequestMapping("/toAdd")
	public String toAdd(UserDo user){
		return "user/userAdd";
	}
	
	@RequestMapping("/add")
    public String add(UserDo user) {
        userService.saveUser(user);
        return "redirect:/list";
    }
	
	@RequestMapping("/toEdit")
	public String toEdit(Model model, Integer id){
		UserDo user = userService.findUserById(id);
		model.addAttribute("user", user);
		return "user/userEdit";
	}
	
	@RequestMapping("/edit")
    public String edit(UserDo user) {
        userService.editUser(user);
        return "redirect:/list";
    }
	
	@RequestMapping("/delete")
    public String delete(Integer id) {
        userService.deleteUser(id);
        return "redirect:/list";//删除内容之后自动调整到list请求,然后再输出到页面。
    }
}
  • return "user/userEdit"; 代表会直接去resources目录下找相关的文件。
  • return "redirect:/list"; 代表转发到对应的controller,这个示例就相当于删除内容之后自动调整到list请求,然后再输出到页面。

页面内容

在resource/templates下创建user文件夹

在user文件夹下创建list.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
	<head>
	    <meta charset="UTF-8"/>
	    <title>userList</title>
	</head>
<body class="container">
	<br/>
	<h1>用户列表</h1>
	<br/><br/>
	<div class="with:80%">
	    <table>
	        <thead>
	        <tr>
	            <th>#</th>
	            <th>UserName</th>
	            <th>Edit</th>
	            <th>Delete</th>
	        </tr>
	        </thead>
	        <tbody>
	        <tr  th:each="user : ${userList}">
	            <th scope="row" th:text="${user.id}"></th>
	            <td th:text="${user.name}"></td>
	            <td><a th:href="@{/toEdit(id=${user.id})}">编辑</a></td>
	            <td><a th:href="@{/delete(id=${user.id})}">删除</a></td>
	        </tr>
	        </tbody>
	    </table>
	</div>
	<div>
	    <div>
	        <a href="/toAdd" th:href="@{/toAdd}">添加</a>
	    </div>
	</div>
</body>
</html>

效果图:

<tr th:each="user : ${userList}"> 这里会从controler层model set的对象去获取相关的内容,th:each表示会循环遍历对象内容。

其实还有其它的写法,读者可以去学习尝试其他写法

在同级目录下添加userAdd作为添加用户界面:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>userAdd</title>
</head>
<body>
	<br/>
	<h2>添加用户</h2>
	<br/>
	<div>
	    <form th:action="@{/add}" th:object="${user}" method="post">
	        <div>
	            <label for="name">用户名:</label>
	            <div>
	                <input type="text" name="name"  id="name"/>
	            </div>
	        </div>
	        <div>
	            <div>
	                <input type="submit" value="提交"/>
	                &nbsp;&nbsp;&nbsp;
	                <a href="/list" th:href="@{/list}">返回</a>
	            </div>
	        </div>
	    </form>
	</div>
</body>
</html>

同理添加userEdit页面作为编辑页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>user</title>
</head>
<body>
	<br/>
	<h2>修改用户</h2>
	<br/>
	<div>
	    <form th:action="@{/edit}" th:object="${user}" method="post">
	        <input type="hidden" name="id" th:value="*{id}" />
	        <div>
	            <label for="name">用户名</label>
	            <div>
	                <input type="text" name="name"  id="name" th:value="*{name}" placeholder="name"/>
	            </div>
	        </div>
	        <div>
	            <div>
	                <input type="submit" value="提交"/>
	                &nbsp; &nbsp; &nbsp;
	                <a href="/list" th:href="@{/list}">返回</a>
	            </div>
	
	        </div>
	    </form>
	</div>
</body>
</html>

效果图:

 这样一个使用jpa和thymeleaf的增删改查示例就完成了。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值