diff --git a/spring-boot-demo-orm-jdbctemplate/README.md b/spring-boot-demo-orm-jdbctemplate/README.md new file mode 100644 index 0000000..99ce53c --- /dev/null +++ b/spring-boot-demo-orm-jdbctemplate/README.md @@ -0,0 +1,193 @@ +# spring-boot-demo-orm-jdbctemplate +依赖 [spring-boot-demo-parent](../spring-boot-demo-parent)、spring-boot-starter-jdbc + +## pom.xml + +```xml + + + 4.0.0 + + spring-boot-demo-orm-jdbctemplate + 0.0.1-SNAPSHOT + jar + + spring-boot-demo-orm-jdbctemplate + Demo project for Spring Boot + + + com.xkcoding + spring-boot-demo-parent + 0.0.1-SNAPSHOT + ../spring-boot-demo-parent/pom.xml + + + + + org.springframework.boot + spring-boot-starter-jdbc + + + com.alibaba + druid-spring-boot-starter + 1.1.9 + + + + + spring-boot-demo-orm-jdbctemplate + + + +``` + +## application.yml + +```yaml +server: + port: 8080 + context-path: /demo +spring: + datasource: + # 启动时自动运行的 SQL 文件 + schema: classpath:init-sql/schema.sql + continue-on-error: true + druid: + url: jdbc:mysql://localhost:3306/spring-boot-demo?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false + username: root + password: root + driver-class-name: com.mysql.jdbc.Driver + # 连接池配置 + # 初始化大小,最小,最大 + initialSize: 5 + minIdle: 5 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + # 打开PSCache,并且指定每个连接上PSCache的大小 + poolPreparedStatements: true + maxPoolPreparedStatementPerConnectionSize: 20 + # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 + filters: stat,wall,log4j + # 监控配置 + web-stat-filter: + enabled: true + url-pattern: /* + exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" + stat-view-servlet: + enabled: true + url-pattern: /sys/druid/* + reset-enable: fasle + login-username: xkcoding + login-password: 123456 + filter: + stat: + log-slow-sql: true + slow-sql-millis: 5000 + merge-sql: true +``` + +## schema.sql + +```mysql +SET FOREIGN_KEY_CHECKS=0; + +DROP TABLE IF EXISTS `jdbctemplate_user`; +CREATE TABLE `jdbctemplate_user` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(32) DEFAULT NULL, + `tel` varchar(11) DEFAULT NULL, + `create_time` datetime DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +INSERT INTO `jdbctemplate_user` VALUES (1, 'klay', '13799008800', '2017-11-13 16:04:39'); +INSERT INTO `jdbctemplate_user` VALUES (2, 'Tome', '18988991234', '2017-11-13 16:13:28'); +``` + +## UserServiceImpl.java + +```java +/** + *

+ * UserServiceImpl + *

+ * + * @package: com.xkcoding.springbootdemoormjdbctemplate.service.impl + * @description: UserServiceImpl + * @author: yangkai.shen + * @date: Created in 2018/5/11 下午3:27 + * @copyright: Copyright (c) 2018 + * @version: V1.0 + * @modified: yangkai.shen + */ +@Service +public class UserServiceImpl implements UserService { + @Autowired + private JdbcTemplate jdbcTemplate; + + @Override + public Integer save(User user) { + String sql = "INSERT INTO jdbctemplate_user (name,tel,create_time) VALUES(?,?,?)"; + return jdbcTemplate.update(sql, user.getName(), user.getTel(), user.getCreateTime()); + } + + @Override + public Integer update(User user) { + String sql = "UPDATE jdbctemplate_user SET name = ?,tel = ? where id = ?"; + return jdbcTemplate.update(sql, user.getName(), user.getTel(), user.getId()); + } + + @Override + public Integer delete(User user) { + String sql = "DELETE FROM jdbctemplate_user where id = ?"; + return jdbcTemplate.update(sql, user.getId()); + } + + @Override + public User findById(Integer id) { + String sql = "SELECT * FROM jdbctemplate_user where id = ?"; + RowMapper rowMapper = new BeanPropertyRowMapper(User.class); + return jdbcTemplate.queryForObject(sql, new Object[]{id}, rowMapper); + } + + @Override + public User findByName(String name) { + String sql = "SELECT * FROM jdbctemplate_user where name = ?"; + RowMapper rowMapper = new BeanPropertyRowMapper(User.class); + return jdbcTemplate.queryForObject(sql, new Object[]{name}, rowMapper); + } + + @Override + public List findAll() { + String sql = "SELECT * FROM jdbctemplate_user"; + List> maps = jdbcTemplate.queryForList(sql); + List ret = Lists.newArrayList(); + maps.forEach(map -> ret.add(BeanUtil.fillBeanWithMap(map, new User(), true, false))); + return ret; + } + + @Override + public List findUserByPage(Integer pageNum, Integer pageSize) { + String sql = "SELECT * FROM jdbctemplate_user LIMIT ?,?"; + Integer offset = (pageNum - 1) * pageSize; + List> maps = jdbcTemplate.queryForList(sql, new Object[]{offset, pageSize}); + List ret = Lists.newArrayList(); + maps.forEach(map -> ret.add(BeanUtil.fillBeanWithMap(map, new User(), true, false))); + return ret; + } +} +``` + +## 其余代码 + +详情请参见本demo。 \ No newline at end of file diff --git a/spring-boot-demo-orm-jdbctemplate/pom.xml b/spring-boot-demo-orm-jdbctemplate/pom.xml new file mode 100644 index 0000000..13bb488 --- /dev/null +++ b/spring-boot-demo-orm-jdbctemplate/pom.xml @@ -0,0 +1,36 @@ + + + 4.0.0 + + spring-boot-demo-orm-jdbctemplate + 0.0.1-SNAPSHOT + jar + + spring-boot-demo-orm-jdbctemplate + Demo project for Spring Boot + + + com.xkcoding + spring-boot-demo-parent + 0.0.1-SNAPSHOT + ../spring-boot-demo-parent/pom.xml + + + + + org.springframework.boot + spring-boot-starter-jdbc + + + com.alibaba + druid-spring-boot-starter + 1.1.9 + + + + + spring-boot-demo-orm-jdbctemplate + + + \ No newline at end of file diff --git a/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/SpringBootDemoOrmJdbctemplateApplication.java b/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/SpringBootDemoOrmJdbctemplateApplication.java new file mode 100644 index 0000000..d8f6363 --- /dev/null +++ b/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/SpringBootDemoOrmJdbctemplateApplication.java @@ -0,0 +1,12 @@ +package com.xkcoding.springbootdemoormjdbctemplate; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootDemoOrmJdbctemplateApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootDemoOrmJdbctemplateApplication.class, args); + } +} diff --git a/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/controller/UserController.java b/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/controller/UserController.java new file mode 100644 index 0000000..b051872 --- /dev/null +++ b/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/controller/UserController.java @@ -0,0 +1,94 @@ +package com.xkcoding.springbootdemoormjdbctemplate.controller; + +import com.xiaoleilu.hutool.util.StrUtil; +import com.xkcoding.springbootdemoormjdbctemplate.model.User; +import com.xkcoding.springbootdemoormjdbctemplate.service.UserService; +import com.xkcoding.springbootdemoormjdbctemplate.vo.R; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Date; +import java.util.List; + +/** + *

+ * UserController + *

+ * + * @package: com.xkcoding.springbootdemoormjdbctemplate.controller + * @description: UserController + * @author: yangkai.shen + * @date: Created in 2018/5/11 下午3:52 + * @copyright: Copyright (c) 2018 + * @version: V1.0 + * @modified: yangkai.shen + */ +@RestController +@RequestMapping("/user") +public class UserController { + + @Autowired + private UserService userService; + + @GetMapping("/save") + public R save() { + User user = new User(); + user.setName("xkcoding"); + user.setTel("18600000000"); + user.setCreateTime(new Date()); + Integer save = userService.save(user); + if (save > 0) { + return R.builder().code(200).msg("添加成功").data(user).build(); + } + return R.builder().code(500).msg("添加失败").data(null).build(); + } + + @GetMapping("/update") + public R update() { + User user = new User(); + user.setId(2); + user.setName(" 修改后的名字 "); + user.setTel("17300000000"); + Integer update = userService.update(user); + if (update > 0) { + return R.builder().code(200).msg("修改成功").data(userService.findById(2)).build(); + } + return R.builder().code(500).msg("修改失败").data(null).build(); + } + + @GetMapping("/delete") + public R delete() { + User user = new User(); + user.setId(1); + Integer delete = userService.delete(user); + + if (delete > 0) { + return R.builder().code(200).msg("删除成功").data(null).build(); + } + return R.builder().code(500).msg("删除失败").data(null).build(); + } + + @GetMapping("/find/{id}") + public R findById(@PathVariable Integer id) { + User user = userService.findById(id); + return R.builder().code(user == null ? 404 : 200).msg(user == null ? StrUtil.format("没有ID为{}的用户", id) : "查询成功").data(user).build(); + } + + @GetMapping("/find") + public R findByName(@RequestParam String name) { + User user = userService.findByName(name); + return R.builder().code(user == null ? 404 : 200).msg(user == null ? StrUtil.format("没有姓名为{}的用户", name) : "查询成功").data(user).build(); + } + + @GetMapping({"", "/"}) + public R findAll() { + List userList = userService.findAll(); + return R.builder().code(userList.isEmpty() ? 404 : 200).msg(userList.isEmpty() ? "暂无用户" : "查询成功").data(userList).build(); + } + + @GetMapping("/page") + public R findByPage(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) { + List userList = userService.findUserByPage(pageNum, pageSize); + return R.builder().code(userList.isEmpty() ? 404 : 200).msg(userList.isEmpty() ? "暂无用户" : "查询成功").data(userList).build(); + } +} diff --git a/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/model/User.java b/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/model/User.java new file mode 100644 index 0000000..3f970db --- /dev/null +++ b/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/model/User.java @@ -0,0 +1,27 @@ +package com.xkcoding.springbootdemoormjdbctemplate.model; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + *

+ * 实体类 + *

+ * + * @package: com.xkcoding.springbootdemoormjdbctemplate.model + * @description: 实体类 + * @author: yangkai.shen + * @date: Created in 2018/5/11 下午3:24 + * @copyright: Copyright (c) 2018 + * @version: V1.0 + * @modified: yangkai.shen + */ +@Data +public class User implements Serializable { + private int id; + private String name; + private String tel; + private Date createTime; +} diff --git a/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/service/UserService.java b/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/service/UserService.java new file mode 100644 index 0000000..99e98a7 --- /dev/null +++ b/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/service/UserService.java @@ -0,0 +1,34 @@ +package com.xkcoding.springbootdemoormjdbctemplate.service; + +import com.xkcoding.springbootdemoormjdbctemplate.model.User; + +import java.util.List; + +/** + *

+ * UserService + *

+ * + * @package: com.xkcoding.springbootdemoormjdbctemplate.service + * @description: UserService + * @author: yangkai.shen + * @date: Created in 2018/5/11 下午3:26 + * @copyright: Copyright (c) 2018 + * @version: V1.0 + * @modified: yangkai.shen + */ +public interface UserService { + Integer save(User user); + + Integer update(User user); + + Integer delete(User user); + + User findById(Integer id); + + User findByName(String name); + + List findAll(); + + List findUserByPage(Integer pageNum, Integer pageSize); +} diff --git a/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/service/impl/UserServiceImpl.java b/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/service/impl/UserServiceImpl.java new file mode 100644 index 0000000..28f397d --- /dev/null +++ b/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/service/impl/UserServiceImpl.java @@ -0,0 +1,84 @@ +package com.xkcoding.springbootdemoormjdbctemplate.service.impl; + +import com.google.common.collect.Lists; +import com.xiaoleilu.hutool.bean.BeanUtil; +import com.xkcoding.springbootdemoormjdbctemplate.model.User; +import com.xkcoding.springbootdemoormjdbctemplate.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.BeanPropertyRowMapper; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + *

+ * UserServiceImpl + *

+ * + * @package: com.xkcoding.springbootdemoormjdbctemplate.service.impl + * @description: UserServiceImpl + * @author: yangkai.shen + * @date: Created in 2018/5/11 下午3:27 + * @copyright: Copyright (c) 2018 + * @version: V1.0 + * @modified: yangkai.shen + */ +@Service +public class UserServiceImpl implements UserService { + @Autowired + private JdbcTemplate jdbcTemplate; + + @Override + public Integer save(User user) { + String sql = "INSERT INTO jdbctemplate_user (name,tel,create_time) VALUES(?,?,?)"; + return jdbcTemplate.update(sql, user.getName(), user.getTel(), user.getCreateTime()); + } + + @Override + public Integer update(User user) { + String sql = "UPDATE jdbctemplate_user SET name = ?,tel = ? where id = ?"; + return jdbcTemplate.update(sql, user.getName(), user.getTel(), user.getId()); + } + + @Override + public Integer delete(User user) { + String sql = "DELETE FROM jdbctemplate_user where id = ?"; + return jdbcTemplate.update(sql, user.getId()); + } + + @Override + public User findById(Integer id) { + String sql = "SELECT * FROM jdbctemplate_user where id = ?"; + RowMapper rowMapper = new BeanPropertyRowMapper(User.class); + return jdbcTemplate.queryForObject(sql, new Object[]{id}, rowMapper); + } + + @Override + public User findByName(String name) { + String sql = "SELECT * FROM jdbctemplate_user where name = ?"; + RowMapper rowMapper = new BeanPropertyRowMapper(User.class); + return jdbcTemplate.queryForObject(sql, new Object[]{name}, rowMapper); + } + + @Override + public List findAll() { + String sql = "SELECT * FROM jdbctemplate_user"; + List> maps = jdbcTemplate.queryForList(sql); + List ret = Lists.newArrayList(); + maps.forEach(map -> ret.add(BeanUtil.fillBeanWithMap(map, new User(), true, false))); + return ret; + } + + @Override + public List findUserByPage(Integer pageNum, Integer pageSize) { + String sql = "SELECT * FROM jdbctemplate_user LIMIT ?,?"; + Integer offset = (pageNum - 1) * pageSize; + List> maps = jdbcTemplate.queryForList(sql, new Object[]{offset, pageSize}); + List ret = Lists.newArrayList(); + maps.forEach(map -> ret.add(BeanUtil.fillBeanWithMap(map, new User(), true, false))); + return ret; + } +} diff --git a/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/vo/R.java b/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/vo/R.java new file mode 100644 index 0000000..8828204 --- /dev/null +++ b/spring-boot-demo-orm-jdbctemplate/src/main/java/com/xkcoding/springbootdemoormjdbctemplate/vo/R.java @@ -0,0 +1,29 @@ +package com.xkcoding.springbootdemoormjdbctemplate.vo; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + *

+ * 统一返回结果类型 + *

+ * + * @package: com.xkcoding.springbootdemoormjdbctemplate.vo + * @description: 统一返回结果类型 + * @author: yangkai.shen + * @date: Created in 2018/5/11 下午3:53 + * @copyright: Copyright (c) 2018 + * @version: V1.0 + * @modified: yangkai.shen + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class R { + private int code; + private String msg; + private Object data; +} diff --git a/spring-boot-demo-orm-jdbctemplate/src/main/resources/application.yml b/spring-boot-demo-orm-jdbctemplate/src/main/resources/application.yml new file mode 100644 index 0000000..e8332df --- /dev/null +++ b/spring-boot-demo-orm-jdbctemplate/src/main/resources/application.yml @@ -0,0 +1,49 @@ +server: + port: 8080 + context-path: /demo +spring: + datasource: + # 启动时自动运行的 SQL 文件 + schema: classpath:init-sql/schema.sql + continue-on-error: true + druid: + url: jdbc:mysql://localhost:3306/spring-boot-demo?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false + username: root + password: root + driver-class-name: com.mysql.jdbc.Driver + # 连接池配置 + # 初始化大小,最小,最大 + initialSize: 5 + minIdle: 5 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + # 打开PSCache,并且指定每个连接上PSCache的大小 + poolPreparedStatements: true + maxPoolPreparedStatementPerConnectionSize: 20 + # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 + filters: stat,wall,log4j + # 监控配置 + web-stat-filter: + enabled: true + url-pattern: /* + exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" + stat-view-servlet: + enabled: true + url-pattern: /sys/druid/* + reset-enable: fasle + login-username: xkcoding + login-password: 123456 + filter: + stat: + log-slow-sql: true + slow-sql-millis: 5000 + merge-sql: true \ No newline at end of file diff --git a/spring-boot-demo-orm-jdbctemplate/src/main/resources/init-sql/schema.sql b/spring-boot-demo-orm-jdbctemplate/src/main/resources/init-sql/schema.sql new file mode 100644 index 0000000..5d5d9b9 --- /dev/null +++ b/spring-boot-demo-orm-jdbctemplate/src/main/resources/init-sql/schema.sql @@ -0,0 +1,13 @@ +SET FOREIGN_KEY_CHECKS=0; + +DROP TABLE IF EXISTS `jdbctemplate_user`; +CREATE TABLE `jdbctemplate_user` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(32) DEFAULT NULL, + `tel` varchar(11) DEFAULT NULL, + `create_time` datetime DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +INSERT INTO `jdbctemplate_user` VALUES (1, 'klay', '13799008800', '2017-11-13 16:04:39'); +INSERT INTO `jdbctemplate_user` VALUES (2, 'Tome', '18988991234', '2017-11-13 16:13:28'); diff --git a/spring-boot-demo-orm-jdbctemplate/src/test/java/com/xkcoding/springbootdemoormjdbctemplate/SpringBootDemoOrmJdbctemplateApplicationTests.java b/spring-boot-demo-orm-jdbctemplate/src/test/java/com/xkcoding/springbootdemoormjdbctemplate/SpringBootDemoOrmJdbctemplateApplicationTests.java new file mode 100644 index 0000000..a98a78b --- /dev/null +++ b/spring-boot-demo-orm-jdbctemplate/src/test/java/com/xkcoding/springbootdemoormjdbctemplate/SpringBootDemoOrmJdbctemplateApplicationTests.java @@ -0,0 +1,16 @@ +package com.xkcoding.springbootdemoormjdbctemplate; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringBootDemoOrmJdbctemplateApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-boot-demo-parent/pom.xml b/spring-boot-demo-parent/pom.xml index 05f3768..1151ff6 100644 --- a/spring-boot-demo-parent/pom.xml +++ b/spring-boot-demo-parent/pom.xml @@ -32,6 +32,7 @@ ../spring-boot-demo-elasticsearch ../spring-boot-demo-template-beetl ../spring-boot-demo-task-schedule + ../spring-boot-demo-orm-jdbctemplate