今天,感谢一哥们的提点,在改代码的时候出现了 数据库查询语句错误的情况, 我就更他说 MySQL ,使用 MyBatis 直接使用 逆向工程进行单表操作就好了。生成的mapper.java 文件、 mapper.xml 文件 以及 model 映射的实体,足够完成所有的单表查询操作。然而他是自己写的 SQL,我改起来有些慌张。
- 自己编写的 SQL ,每一条语句要到 数据库工具中 去查看能否执行,并且能否找到正确的信息。
- 数据库表的内容和实体类的映射。表字段 real_name,映射实体类中的 realName 。
- SpringBoot 中的映射 。
### application.properties
mybatis.configuration.map-underscore-to-camel-case:true // 开启驼峰映射
mybatis.configuration.mapperLocations: mybatis/**/*Mapper.xml // 映射 mapper.xml
mybatis.configuration.typeAliasesPackage: cn.chao // 别名
### Mapper 接口
@Mapper
public interface UserDAO {
String TABLE_NAME = "user";
String INSERT_FIELDS = "name, password, salt, head_url";
String SELECT_FIELDS = "id, name, password, salt, head_url";
@Insert({"insert into", TABLE_NAME, "(", INSERT_FIELDS, ") values(#{name}, #{password}, #{salt}, #{headUrl})"})
int addUser(User user);
}
### 测试类
public class InitDBTest {
@Autowired
UserDAO userDAO;
public void contextLoads() {
User user = new User();
user.setName("user1"); // 用户账号
user.setPassword(""); // 用户密码
user.setSalt(""); // md5 用的盐
user.setHeadUrl("xxx.png"); // 图片地址。数据库字段 head_url ,实体类 headUrl 。
userDAO.addUser(user);
}
}
- MyBatis 的配置文件的方式
### 配置在 MyBatis 的 SqlMapConfig.xml
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
- 通过配置属性来完成映射,Mybatis给我们提供了一种映射方式,如果属性的命名是遵从驼峰命名法的,数据列名遵从下划线命名。
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
Configuration configuration = new Configuration();
configuration.setMapUnderscoreToCamelCase(true);
sqlSessionFactoryBean.setConfiguration(configuration);
- 接下来说一波自己的编写的没有使用映射配置的 SQL 的代码。
- SQL 语句查询数据库的字段中的内容是不区分大小写的。
- AS 前边就是数据库表中的字段,AS 后边就是我们写的实体类的属性名称。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.edu.sjzc.dao.UserDao">
<!-- 根据姓名模糊查询客户 -->
<select id="findUserByRealName" parameterType="cn.edu.sjzc.po.User"
resultType="cn.edu.sjzc.po.User">
SELECT
user_id as 'userId',
username as 'userName',
PASSWORD as 'passWord',
real_name as 'realName',
user_type as 'userType',
sex as 'sex',
tel as 'tel'
FROM USER WHERE real_name LIKE '%#{realName}%'
limit #{start},#{rows};
</select>
<!-- 更新客户信息 -->
<update id="updateUser" parameterType="cn.edu.sjzc.po.User">
update user
<set>
<if test="userName!=null">
username=#{userName},
</if>
<if test="passWord!=null">
password=#{passWord},
</if>
<if test="sex!=null">
sex=#{sex},
</if>
<if test="realName!=null">
real_name=#{realName},
</if>
<if test="tel!=null">
tel=#{tel},
</if>
<if test="userType!=null">
user_type=#{userType},
</if>
</set>
where user_id=#{userId}
</update>
<!-- 根据id删除客户 -->
<delete id="delUser" parameterType="Integer">
delete
from user
where user_id=#{userId}
</delete>
</mapper>

本文介绍如何在SpringBoot项目中使用MyBatis进行数据库操作,包括配置文件设置、Mapper接口定义及XML文件编写等。重点讨论了如何解决数据库字段与实体类属性映射问题,并给出具体示例。
253

被折叠的 条评论
为什么被折叠?



