這篇文章主要講解了Spring boot2+jpa+thymeleaf如何實現(xiàn)增刪改查,內(nèi)容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
創(chuàng)新互聯(lián)長期為千余家客戶提供的網(wǎng)站建設(shè)服務,團隊從業(yè)經(jīng)驗10年,關(guān)注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務;打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為魏縣企業(yè)提供專業(yè)的成都做網(wǎng)站、網(wǎng)站制作、成都外貿(mào)網(wǎng)站建設(shè),魏縣網(wǎng)站改版等技術(shù)服務。擁有10余年豐富建站經(jīng)驗和眾多成功案例,為您定制開發(fā)。
一、pom.xml引入相關(guān)模塊web、jpa、thymeleaf、oracle:
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-data-jpa com.oracle ojdbc8 12.2.0.1
二、application.properties配置
server.port = 9001 spring.datasource.driver-class-name = oracle.jdbc.driver.OracleDriver spring.datasource.url = jdbc:oracle:thin:@127.0.0.1:1521:testdb spring.datasource.username = dev spring.datasource.password = dev spring.jpa.hibernate.ddl-auto = update spring.jpa.show-sql = true spring.thymeleaf.cache = false
說明:
1、由于本機的8080已經(jīng)被使用,修改一下端口號為9001。
2、hibernate.hbm2ddl.auto參數(shù)有四個值:
create: 每次加載hibernate時都會刪除上一次的生成的表,然后根據(jù)你的model類再重新來生成新表,哪怕兩次沒有任何改變也要
這樣執(zhí)行,這就是導致數(shù)據(jù)庫表數(shù)據(jù)丟失的一個重要原因。
create-drop :每次加載hibernate時根據(jù)model類生成表,但是sessionFactory一關(guān)閉,表就自動刪除。
update:最常用的屬性,第一次加載hibernate時根據(jù)model類會自動建立起表的結(jié)構(gòu)(前提是先建立好數(shù)據(jù)庫),以后加載
hibernate時根據(jù) model類自動更新表結(jié)構(gòu),即使表結(jié)構(gòu)改變了但表中的行仍然存在不會刪除以前的行。要注意的是當部署到服務器后,表結(jié)構(gòu)是不會被馬上建立起來的,是要等 應用第一次運行起來后才會。
validate :每次加載hibernate時,驗證創(chuàng)建數(shù)據(jù)庫表結(jié)構(gòu),只會和數(shù)據(jù)庫中的表進行比較,不會創(chuàng)建新表,但是會插入新值。
3、show-sql 是否打印出自動生產(chǎn)的SQL,方便調(diào)試的時候查看
4、propertiesspring.thymeleaf.cache=false是關(guān)閉thymeleaf的緩存,不然在開發(fā)過程中修改頁面不會立刻生效需要重啟,生產(chǎn)
可配置為true。
三、啟動類需要添加Servlet的支持
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class DemoApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(DemoApplication.class); } public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
四、數(shù)據(jù)庫層代碼
1、實體類映射數(shù)據(jù)庫表
package com.example.demo.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotEmpty; import org.hibernate.validator.constraints.Length; @Entity @Table(name = "userinfo") public class User { @Id @GeneratedValue private long id; @Column(nullable = false, unique = true) @NotEmpty(message="用戶名不能為空") private String userName; @Column(nullable = false) @NotEmpty(message="密碼不能為空") @Length(min=6, message="密碼長度不能少于6位") private String password; @Column(nullable = false) private int age; //必須有構(gòu)造 public User() { } public long getId() { return id; } public User setId(long id) { this.id = id; return this; } public String getUserName() { return userName; } public User setUserName(String userName) { this.userName = userName; return this; } public String getPassword() { return password; } public User setPassword(String password) { this.password = password; return this; } public int getAge() { return age; } public User setAge(int age) { this.age = age; return this; } }
2、繼承JpaRepository類會自動實現(xiàn)很多內(nèi)置的方法
package com.example.demo.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.example.demo.entity.User; public interface UserRepository extends JpaRepository{ User findById(long id); void deleteById(Long id); }
五、業(yè)務層
service調(diào)用jpa實現(xiàn)相關(guān)的增刪改查,實際項目中service層處理具體的業(yè)務代碼。
1、UserService.java
package com.example.demo.service; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import com.example.demo.entity.User; public interface UserService { public PagegetUserPage(Pageable pageable); public List getUserList(); public User findUserById(long id); public void save(User user); public void edit(User user); public void delete(long id); }
2、UserServiceImpl.java
package com.example.demo.service.impl; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import com.example.demo.entity.User; import com.example.demo.repository.UserRepository; import com.example.demo.service.UserService; @Service public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Override public PagegetUserPage(Pageable pageable) { return userRepository.findAll(pageable); } @Override public List getUserList() { return userRepository.findAll(); } @Override public User findUserById(long id) { return userRepository.findById(id) ; } @Override public void save(User user) { userRepository.save(user); } @Override public void edit(User user) { userRepository.save(user); } @Override public void delete(long id) { userRepository.deleteById(id); } }
六、控制層
package com.example.demo.web.controller; import java.util.List; import javax.annotation.Resource; import javax.validation.Valid; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.example.demo.entity.User; import com.example.demo.service.UserService; @Controller public class UserController { @Resource UserService userService; @RequestMapping("/") public String index() { return "redirect:/list"; } @RequestMapping("/list") public String list(Model model) { Listusers=userService.getUserList(); model.addAttribute("users", users); /*int page=1,size=2; Sort sort = new Sort(Direction.DESC, "id"); Pageable pageable = PageRequest.of(page, size, sort); model.addAttribute("users", pageable);*/ return "user/list"; } @RequestMapping("/toAdd") public String toAdd() { return "user/userAdd"; } @RequestMapping("/add") public @ResponseBody User add(@Valid User user, BindingResult result) { if (result.hasErrors()) { List list = result.getAllErrors(); for (ObjectError error : list) { System.out.println(error.getDefaultMessage()); } return null; } userService.save(user); return user; } @RequestMapping("/toEdit") public String toEdit(Model model,Long id) { User user=userService.findUserById(id); model.addAttribute("user", user); return "user/userEdit"; } @RequestMapping("/edit") public String edit(User user) { userService.edit(user); return "redirect:/list"; } @RequestMapping("/delete") public String delete(Long id) { userService.delete(id); return "redirect:/list"; } }
七、頁面
1、列表頁 list.hmtl
2、新增頁 userAdd.html
user
添加用戶
3、修改頁 userEdit.html
user
修改用戶
看完上述內(nèi)容,是不是對Spring boot2+jpa+thymeleaf如何實現(xiàn)增刪改查有進一步的了解,如果還想學習更多內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。