一、文件结构:
二、实体类
package com.example.demo.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "user") public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private Long id; @Column(name = "username") private String userName; @Column(name = "password") private String passWord; public User() { super(); } public User(String userName, String passWord) { super(); this.userName = userName; this.passWord = passWord; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } }
三、Dao
package com.example.demo.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.example.demo.domain.User; public interface UserRepository extends JpaRepository<User, Long> { User findByUserName(String userName); }
四、Controller
package com.example.demo.controller; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.example.demo.dao.UserRepository; import com.example.demo.domain.User; @RestController @RequestMapping("user") public class UserController { @Autowired private UserRepository userRepository; @RequestMapping("/getAllUser") @ResponseBody public List<User> findAll() { List<User> list = new ArrayList<User>(); list = userRepository.findAll(); return list; } @RequestMapping("/getByUserName") @ResponseBody public User getByUserName(String userName) { User user = userRepository.findByUserName(userName); return user; } }
五、application.properties配置
# MySQL Connection Configuration spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test spring.datasource.username=root spring.datasource.password=12345678 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.properties.hibernate.hbm2ddl.auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.show-sql= true
六、pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!--mysql驱动连接 jar包--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
七、表结构
八、启动服务后测试
http://localhost:8080//user/getByUserName?userName=mike
http://localhost:8080//user/getAllUser
结束!
标签:userName,SpringBoot,spring,public,User,MySQL,import,连接,String From: https://www.cnblogs.com/aaronthon/p/18006484