旨在熟悉springboot项目简单得从0-1的过程
从spring initializr 中创建springboot项目
从spring initializr 中创建springboot项目,也可以从http://start.spring.io/ 网站创建再导入,这里主要讲从initializr创建项目
创建项目结构
引入web dependency
org.springframework.boot
spring-boot-starter-web
数据操作,引入jpa和mysql
org.springframework.boot
spring-boot-starter-data-jpa
mysql
mysql-connector-java
在application.properties中配置数据库信息
# db connection information start
server.port=8080
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=Abcd1234
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database=MYSQL
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
# db connection information end
创建user entity作为测试
@Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="id")
private long id;
@Column(name="username", unique = true)
private String username;
@Column(name="password")
private String 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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
设计dao进行数据操作
public interface UserDao extends JpaRepository {
User findUserByUsername(String username);
}
编写服务类
@Component
public class UserService {
@Autowired
private UserDao userDao;
public User getUserByUsername(String username) {
return userDao.findUserByUsername(username);
}
}
编写controller实现请求
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/{username}")
public User findUserByUsername(@PathVariable String username) {
return this.userService.getUserByUsername(username);
}
}
引入thymeleaf来进行页面显示
org.springframework.boot
spring-boot-starter-thymeleaf
并且需要在application.properties 中配置如下信息
# thymeleaf start
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
# thymeleaf end
如上过程完成,一个简单的springboot 数据库交互和页面显示的helloworld就出来了
代码已经上传到github
https://github.com/lishang08/spring-boot/tree/master/helloworld