SpringBoot 急速构建项目,真的是用了才知道,搭配JPA做为持久层,一简到底!
下面记录项目的搭建,后续会添加NOSQL redis,搜索引擎elasticSearch,等等,什么不过期就加什么。html
开发工具idea、项目构建gradle、模板引擎thymeleafmysql
1.【new】 -> 【product】 -> 选择Spring Initializr -> 【next】redis
2.填写Group,Artifact,Type ->【next】spring
3.导包sql
好了
如今的项目结构segmentfault
BootjpaApplication 是项目的启动类
resources/templates/ 文件夹是放页面的
build.gradle 存放jar包坐标浏览器
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.properties.hibernate.hbm2ddl.auto=update
配置完成,写个controller试试看app
@RestController public class HelloBootController { @RequestMapping("helloBoot") public String helloBoot(){ return "Hello Boot-JPA"; } }
在BootjpaApplication文件上启动elasticsearch
@RestController注解,代替@Controller+@ResponseBody
那么返回页面就直接用@Controller就行了ide
注解和hibernate同样。
@Entity public class User { private long id; private String name; private String passWord; private String email; @Id @GeneratedValue public long getId() { return id; } 。。。。。 }
如今,就是见证奇迹的时刻!
dao层继承JpaRepository便可
public interface UserRepository extends JpaRepository<User,Long> { }
什么!这就完了??对,低调
controller层,service层跳过。
@Controller public class HelloBootController { @Autowired UserRepository userRepository; @RequestMapping("/toHello") public String toHello(ModelMap modelMap){ userRepository.save(new User("Mshu","123456","zhuiqiu95@foxmail.com")); List<User> users = userRepository.findAll(); modelMap.put("users",users); return "helloBoot"; //页面地址 } }
至于页面,默认是在resources/templates/下的html,试图解析器已经配置默认配置好的。
前缀:resources/templates/ 后缀:html
那咱们就在resources/templates/下新建一个名为helloBoot.html
的页面
注意<html xmlns:th="http://www.thymeleaf.org " lang="en">引入thymeleaf
用到了thymeleaf语法遍历。
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table > <tr th:each="user,userState : ${users}"> <td style="border: 1px solid seagreen" th:text="${user.name}"></td> <td style="border: 1px solid seagreen" th:text="${user.passWord}"></td> <td style="border: 1px solid seagreen" th:text="${user.email}"></td> </tr> </table> </body> </html>
启动,输入地址,回车!
咱们须要将application.properties里面配置的数据注入到类中能够这么作,
如下是一段application.properties中的数据;
#elasticsearch cluster.name=elasticsearch elasticsearch.ip=127.0.0.1 elasticsearch.port=9300
在类中使用@Value注入,记住使用${}包裹:
@Component public class ELClient { @Value("${cluster.name}") private String clusterName; @Value("${elasticsearch.ip}") private String elacticSearchIp; @Value("${elasticsearch.port}") private Integer elacticSearchPort; }
刚刚dao层明明只写了一个接口没有写任何方法,怎么就能调用save(),findAll()呢,
对JPA默认了许多基础增删改查方法,直接调用便可。
怎么写除了默认给出的方法之外怎么写呢,
public interface UserRepository extends JpaRepository<User,Long> { User findByName(String name); }
调用的话直接
User user = userRepository.findByName("Mshu");
那么怎么作的映射的,它怎么知道个人参数name对应表里的name,原来名字同样就能够映射,好像颇有道理
没错就那么简单,这种写法太hibernate了。