给类起别名、获得新增数据的id、log4j显示sql语句【MyBatis笔记六】

目录

给类起别名

获得新增数据的id

log4j 日志显示 sql语句 作用是查看 debug sql 语句


给类起别名

为了在 StudentMapper.xml 中 resultType="com.yuyu.bean.Student" 太多的时候方便管理
<select id="findById" parameterType="int" resultType="com.yuyu.bean.Student">
    select * from student where studentid=#{id}
</select>
在 mybatis.xml 中给类起别名
<typeAliases>
    <!—给实体类起别名 -->
    <typeAlias type="com.yuyu.bean.Student" alias="stu"></typeAlias>  <!-- 这样在 StudentMapper.xml 中使用时可以只写别名 stu -->
    <!--指定哪些包的类可以使⽤别名,默认别名:类名⾸字⺟⼩写(实际使⽤的时候,全部⼩写也可以做结果映射) -->
    <package name="com.yuyu.bean"></package>   <!-- 这样在 StudentMapper.xml 中使用时可以只写 bean 包下类的名称(类名⾸字⺟⼩写) -->
 </typeAliases>

 

获得新增数据的id

适⽤于可以⾃增的主键列上
<insert useGeneratedKeys="true" keyProperty="userid">
        通过自增的方式获取         获得的值设置映射到程序上的名称

<insert id="insertStudent" parameterType="com.yuyu.bean.Student" useGeneratedKeys="true" keyProperty="studentId">
    insert into student(studentno,stuname) values(#{studentNo},#{stuName})
</insert>
Student student = new Student();
student.setStudentNo("s00114");
student.setStuName("谢大脚4");
int insert = session.insert("com.yuyu.dao.StudentDao.insertStudent", student);
session.commit();
System.out.println("insert="+insert);
//通过 mapper.xml 中的 keyProperty 得到新增数据 id
System.out.println("studentid="+student.getStudentId());

 

log4j 日志显示 sql语句 作用是查看 debug sql 语句

1.添加 jar 包

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.5</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.12</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

2.配置 log4j.properties 文件

log4j.rootLogger=DEBUG, Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

操作数据库时控制台输出:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值