一、CRUD操作
映射文件
<!-- int addUser(); -->
<insert id="addUser">
insert into t_user values(null,'张三','123456')
</insert>
<!-- int deleteUserById();-->
<delete id="deleteUserById">
delete from t_user where id = 3
</delete>
<!--
int updateUser();-->
<update id="updateUser">
update t_user set username = '王五' where id = 1
</update>
<!-- 查询方法都要设置结果集 -->
<!-- List<User> getAllUser();-->
<!-- resultType : 默认映射关系 表中字段 与 实体类属性名一致
表中的字段与类属性名一致,会自动装配
resultMap : 自定义的映射关系 表中字段 与 实体类属性名不一致
表中的字段与类属性名不同
-->
<select id="getAllUser" resultType="user">
select * from t_user
</select>
<!-- User getUser() -->
<select id="getUser" resultType="user">
select * from t_user where id = 1
</select>
mapper接口
public interface UserMapper {
int addUser();
int deleteUserById();
int updateUser();
List<User> getAllUser();
User getUser();
}
二、配置log4j日志
1.配置log4j 依赖
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2.配置文件 ,文件名为log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
三、创建SqlSession工具类来获取SqlSession
public class SQLSessionUtils {标签:int,CRUD,id,--,SqlSession,user,mybatis,操作,log4j From: https://blog.51cto.com/u_15497049/5878330
public static SqlSession getSqlSession() {
SqlSession sqlSession = null;
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
// openSession(true) 设置为自动提交事务
sqlSession = factory.openSession(true);
} catch (IOException e) {
e.printStackTrace();
}
return sqlSession;
}
}