麒麟v10 上部署 TiDB v5.1.2 生产环境优化实践
914
2023-07-08
SpringBoot怎么引入mybatis与连接Mysql数据库
创建一个SpringBoot项目
其他不赘叙了,引入MyBaties、MySql依赖
创建mysql表
CREATE TABLE sp_users( `id` INT PRIMARY KEY, `username` VARCHAR(30), `age` INT);登录后复制
刚开始一直出现这个错误,弄的我怀疑人生,结果是最后一行不能加',' ,物是人非。
INSERT INTO sp_users(id,`username`,`age`) VALUES(1,"张三",11);INSERT INTO sp_users(id,`username`,`age`) VALUES(2,"李四",21);INSERT INTO sp_users(id,`username`,`age`) VALUES(3,"游坦之",800);登录后复制
编写实体类
因为引入了Lombok,所以直接用了
package com.you.domain;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import lombok.ToString;@Data@NoArgsConstructor@AllArgsConstructor@ToStringpublic class user { private int id; private String username; private int age;}登录后复制
配置application.yaml
#datasourcespring: datasource: url: jdbc:mysql:///springboot?serverTimezone=UTC username: root password: 你的密码 driver-class-name: com.mysql.cj.jdbc.Driver
配置Mapper
方式一,创建UserMapper接口
package com.you.mapper;import com.you.domain.User;import org.apache.ibatis.annotations.Mapper;import org.apache.ibatis.annotations.Select;import org.springframework.stereotype.Repository;import java.util.List;@Mapper@Repositorypublic interface UserMapper { @Select("select * from sp_users") public List
配置测试类
package com.you.boot;import com.you.boot.domain.User;import com.you.boot.mapper.UserMapper;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import java.util.List;@SpringBootTestclass BootMybatis03ApplicationTests { @Autowired private UserMapper userMapper; @Test public void testFindAll() { List
效果图
方法二 XML文件配置
编写xml文件,namespace一定要复制全路径,Copy/Copy Reference
编写UserXmlMapper接口,@Repository的作用是解决在测试类内爆红,虽然爆红不影响程序的运行。
package com.you.boot.mapper;import com.you.boot.domain.User;import org.apache.ibatis.annotations.Mapper;import org.springframework.stereotype.Repository;import java.util.List;@Mapper@Repositorypublic interface UserXmlMapper { public List
配置yaml,*Mapper值得是所有后缀是Mapper的xml文件
mybatis: mapper-locations: classpath:mapper/*Mapper.xml type-aliases-package: com.you.boot.domain
编写测试类
package com.you.boot;import com.you.boot.domain.User;import com.you.boot.mapper.UserMapper;import com.you.boot.mapper.UserXmlMapper;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import java.util.List;@SpringBootTestclass BootMybatis03ApplicationTests { @Autowired private UserXmlMapper userXmlMapper; @Test public void testFindAll2() { List
效果
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。