这里面采用jdbcTemplate来作为数据库的访问功能,dao只简单包括用户的登录、news的增删改查。
1、pom依赖
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
</dependencies>
这里是主要是Springboot的依赖和数据库的。
1、配置数据库连接application.yml
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot
username: root
password: root
2、编写model
public class User {
private int id;
private String username;//
private String passsword;//
// 忽略set get
}
public class News {
private int id;//
private String title;//标题
private String content;//内容
// 忽略set get
}
3、编写dao
@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public User getByUsername(String username) {
List<User> list = jdbcTemplate.query("select * from t_user where username = ?", new Object[]{username}, new BeanPropertyRowMapper(User.class));
return list.size() > 0 ? list.get(0) : null;
}
}
@Repository
public class NewsDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public int add(News news) {
String sql = "insert into t_news(title,content) values(:title,:content)";
return new NamedParameterJdbcTemplate(jdbcTemplate).update(sql, new BeanPropertySqlParameterSource(news));
}
public int update(News news) {
String sql = "update t_news SET title=:title,content=:content WHERE id=?";
return new NamedParameterJdbcTemplate(jdbcTemplate).update(sql, new BeanPropertySqlParameterSource(news));
}
public int delete(int id) {
return jdbcTemplate.update("DELETE from t_news where id=?", id);
}
public News get(int id) {
List<News> list = jdbcTemplate.query("select * from t_news where id = ?", new Object[]{id}, new BeanPropertyRowMapper(News.class));
return list.size() > 0 ? list.get(0) : null;
}
public List<News> list() {
List<News> list = jdbcTemplate.query("select * from t_news", new BeanPropertyRowMapper(News.class));
return list;
}
}
4、编写service
@Service
public class UserService {
@Autowired
private UserDao userDao;
public User getByUsername(String username) {
return userDao.getByUsername(username);
}
}
@Service
public class NewsService {
@Autowired
private NewsDao newsDao;
public int add(News news) {
return newsDao.add(news);
}
public int update(News news) {
return newsDao.update(news);
}
public int delete(int id) {
return newsDao.delete(id);
}
public News get(int id) {
return newsDao.get(id);
}
public List<News> list() {
return newsDao.list();
}
}