springboot08-jpa-mysql
1.主要pom依赖:
<!--jpa--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
2.userDao:
public interface UserDao extends JpaRepository<User, Long>{ User findByUserName(String userName); User findByUserNameAndPassword(String userName, String password); }
这里继承JpaRepository后,会有主要的增删改查方法,还有查询所有list(), 分页查询list() 等基础方法。如果要自定义方法,可根据jpa标准来定义,比如:
//根据用户名查询单个用户: User findOneByUserName(String userName);
//根据用户名查询多个用户: List<User> findAllByUserName(String userName);
3.测试:
@RunWith(SpringRunner.class) @SpringBootTest(classes = MainApp.class) public class ServiceTest { @Autowired private UserDao userDao; @Autowired private UserService userService; private ObjectMapper objectMapper = new ObjectMapper(); @Test public void testAll() throws JsonProcessingException { this.saveUser(); this.list(); } private void saveUser() throws JsonProcessingException { User admin = new User(); admin.setUserName("admin"); admin.setPassword("admin"); User adminSave = userDao.save(admin); System.out.println("admin save--->:" + objectMapper.writeValueAsString(adminSave)); User user = new User(); user.setUserName("user"); user.setPassword("user"); User userSave = userDao.save(user); System.out.println("user save--->:" + objectMapper.writeValueAsString(userSave)); } private void list() throws JsonProcessingException { List<User> userList = userService.userList(); System.out.println("用户列表:" + objectMapper.writeValueAsString(userList)); } }
结果:
Hibernate: insert into user (password, user_name) values (?, ?) admin save--->:{"id":1,"userName":"admin","password":"admin"} Hibernate: insert into user (password, user_name) values (?, ?) user save--->:{"id":2,"userName":"user","password":"user"} Hibernate: select user0_.id as id1_0_, user0_.password as password2_0_, user0_.user_name as user_nam3_0_ from user user0_ 用户列表:[{"id":1,"userName":"admin","password":"admin"},{"id":2,"userName":"user","password":"user"}]
源码地址:https://github.com/yangzhenlong/mySpringBootDemo
逃避不一定躲得过,面对不一定最难过