目录
DAO(作为存储库):使用Spring Boot时,不需要具体的DAO实现或JdbcUtils
COMMON(应用配置):JdbcUtils 与 JdbcTemplate bean(放入config包)
改包名(可改可不改) | common | config |
添加注解 | pojo | pojo |
添加注解 | service | service |
添加注解 | exception | exception |
替换 | servlet | controller |
添加注解 | dao | dao |
添加注解 | sercurity | sercurity |
POJO(作为实体): 添加注释@Entity @Id
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class EasUser {
@Id
private Long id;
private String username;
private String password; // 考虑使用散列存储密码以提高安全性
// getters 和 setters
}
DAO(作为存储库):使用Spring Boot时,不需要具体的DAO实现或JdbcUtils
COMMON(应用配置):JdbcUtils 与 JdbcTemplate
bean(放入config包)
JpaRepository
处理了大多数常见的数据访问模式,如果需要针对JDBC的特定配置或工具,可以在配置中配置一个JdbcTemplate
bean(一般不需要,可以不用增加)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
@Configuration
public class JdbcConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/yourDatabase");
dataSource.setUsername("username");
dataSource.setPassword("password");
return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
exception(自定义异常)
sercurity
servlet :换为controller
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/login")
public ResponseEntity<?> loginUser(@RequestParam String username, @RequestParam String password) {
EasUser user = userService.loginUser(username, password);
if (user != null) {
return ResponseEntity.ok(user);
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
}