接下来我们学习spring boot 集成一个数据库框架 mybatis。 上一篇 点击打开链接中讲到没有集成其它数据库框架,发现了一个小意外,这里注明一下。
@Override public String saveUser(SystemUser user) { final String sql = "insert into system_user(uuid,username,password,isRoot,registerDate,status) values(?,?,?,?,?,?)"; user.setUuid(UUID.randomUUID().toString().replace("-","")); jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(sql); ps.setString(1, user.getUuid()); ps.setString(2, user.getUsername()); ps.setString(3,user.getPassword()); ps.setString(4,user.getIsRoot()); //ps.setDate(5,new java.sql.Date(user.getRegisterDate().getTime()));//丢失时分秒 ps.setString(5,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(user.getRegisterDate())); ps.setInt(6,user.getStatus()); return ps; } }); return user.getUuid(); }
直接插入sql.Date会导致丢失时分秒,所以可以格式化日期成字符串,也可以顺利插入数据库中。依旧是datetime类型。
不多说了,接下来集成mybatis
mysql mysql-connector-java 5.1.44 com.alibaba druid 1.0.31 org.mybatis.spring.boot mybatis-spring-boot-starter 1.1.1
#mysql spring.datasource.driver-class-name= com.mysql.jdbc.Driver spring.datasource.url=jdbc\:mysql\://localhost\:3306/dadmin?useUnicode\=true&characterEncoding\=UTF-8 spring.datasource.username=root spring.datasource.password=123456 #druid spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.filters=stat spring.datasource.maxActive= 20 spring.datasource.initialSize= 1 spring.datasource.maxWait= 60000 spring.datasource.minIdle =1 spring.datasource.timeBetweenEvictionRunsMillis= 60000 spring.datasource.minEvictableIdleTimeMillis=300000 spring.datasource.validationQuery= select 'x' spring.datasource.testWhileIdle= true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn= false spring.datasource.poolPreparedStatements=true spring.datasource.maxOpenPreparedStatements= 20
@SpringBootApplication @EnableTransactionManagement @MapperScan("com.dashuai.springboot.mapper") public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } }
这里添加了一个注解@MapperScan,用于扫描mapper的。
public interface SystemUserMapper { @Select("select * from system_user where username=#{username}") //@Result 修饰返回的结果集,关联实体类属性和数据库字段一一对应,如果实体类属性和数据库属性名保持一致,就不需要这个属性来修饰。 SystemUser findUserByUsername(String username); @Select("select * from system_user") @Results({ @Result(property = "uuid", column = "uuid", javaType = String.class), @Result(property = "username", column = "username",javaType = String.class), @Result(property = "password", column = "password",javaType = String.class), @Result(property = "isRoot", column = "isRoot",javaType = String.class), @Result(property = "registerDate", column = "registerDate",javaType = java.util.Date.class), @Result(property = "status", column = "status",javaType = Integer.class), }) List那么上述SystemUserMapper我们采用注解的方式。做了一个简单的介绍。findAllUser(); @Insert("insert into system_user(uuid,username,password,isRoot,registerDate,status) " + " values(#{uuid}, #{username}, #{password},#{isRoot},#{registerDate},#{status})") void saveUser(SystemUser user); @Delete("delete from system_user where uuid =#{uuid}") void deleteUserByUUID(String uuid); @Update("update system_user set password=#{password},status=#{status} where uuid=#{uuid}") void updateUser(SystemUser user);
接下来是service层
public interface SystemUserService { SystemUser findUserByUsername(String username); List依旧不变findAllUser(); String saveUser(SystemUser user); void deleteUserByUUID(String uuid); void updateUser(SystemUser user); }
@Service("systemUserServiceMyBatis") public class SystemMyBatisUserServiceImpl implements SystemUserService { @Autowired private SystemUserMapper SystemUserMapper; @Transactional(readOnly = true) @Override public SystemUser findUserByUsername(String username) { return SystemUserMapper.findUserByUsername(username); } @Transactional(readOnly = true) @Override public ListService层的实现,很简单的完成了。findAllUser() { return SystemUserMapper.findAllUser(); } @Transactional @Override public String saveUser(SystemUser user) { SystemUserMapper.saveUser(user); return user.getUuid(); } @Transactional @Override public void deleteUserByUUID(String uuid) { SystemUserMapper.deleteUserByUUID(uuid); } @Transactional @Override public void updateUser(SystemUser user) { SystemUserMapper.updateUser(user); } }
难怪要用框架,你看看使用mybatis,我就在注解里面写写sql语句,就完成了。
这个小错误请无视,还有就是 变量名与类名是相同的。
编写测试类
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class TestMyBatis { Logger logger= LoggerFactory.getLogger(getClass()); @Resource(name="systemUserServiceMyBatis") SystemUserService systemUserService; @Test public void saveUser1(){ SystemUser user = new SystemUser(); user.setStatus(0); user.setUuid(UUID.randomUUID().toString().replace("-","")); user.setRegisterDate(new Date()); user.setPassword("123456"); user.setIsRoot("0"); user.setUsername("testZhan"); String uuid= systemUserService.saveUser(user); logger.info("增加成功:uuid:{}",uuid); } @Test public void findUser1(){ SystemUser user = systemUserService.findUserByUsername("testZhang"); logger.info("user:{}",user); } @Test public void findUser2(){ List我们设置一下日志list = systemUserService.findAllUser(); logger.info("userlist:{}",list); } @Test public void updateUser(){ SystemUser user = systemUserService.findUserByUsername("testZhang"); user.setPassword("1234567"); user.setStatus(1); systemUserService.updateUser(user); } @Test public void deleteUser(){ systemUserService.deleteUserByUUID("cbb0759e58114171bb33437c7db2a276"); }
logging.file=mylog.log logging.level.root=info logging.level.org.springframework=info logging.level.com.dashuai.springboot.mapper=debug看看日志输出吧
注解虽然简单,但是有时候业务逻辑复杂,并不是简单的字符串sql就能处理的,所以我研究了一下动态sql,是如何做的呢。
新建一个类
public class DynamicSQLProvider { public String getFindUserByUsernameSQL(){ return "select * from system_user where username=#{username}"; } public String getGoodFindUserByUsernameSQL(){ return new SQL(){ { SELECT("*"); FROM("system_user"); WHERE("username=#{username}"); } }.toString(); } }上面两个方法都行,有时用纯字符串容易出错,所以用下面的。但两种方式都可以
怎么用呢。看下面
public interface SystemUserMapper { @SelectProvider(type = DynamicSQLProvider.class,method = "getGoodFindUserByUsernameSQL") SystemUser findUserByUsername(String username);使用注解 @SelectProvider方式简单搞定。
越来越觉得 spring boot 强大一塌糊涂。以前觉得 mybatis 集成spring什么的,到处拷贝配置,拷贝什么的,哎。 现在看来简单的一塌糊涂嘛。 spring boot 给你100个赞啊。