Mybatis入门
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录
Mybatis工程搭建
Mybatis是对JDBC轻量级的封装
性能:JDBC>Mybatis>Hibernate
Mybatis半自动框架 自定义sql
Hibernate全自动的 全靠配置文件,一般都是全字段,配置映射关系
功能:Hibernate>Mybatis>JDBC
步骤:
1.创建maven工程
2.导入jar包/导入maven坐标
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--mybaits核心包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--msyql的驱动-->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.2.0</version>
</dependency>
<!--日志:记录应用程序所有的执行过程-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
3.创建实体类
4.创建核心配置文件 mybatis-config.xml jdbc.properties log4j.properties
jdbc.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/gymmanagementsystem
username=root
password=123456
log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\\Learn\\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--如果有,第一步必须先引入外部properties文件-->
<properties resource="jdbc.properties"></properties>
<!-- 一旦mybatis和Spring整合,environments则不需要再单独提供 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<!-- <property name="driver" value="com.mysql.cj.jdbc.Driver"/>-->
<!-- <property name="url" value="jdbc:mysql://localhost:3306/sjt2405"/>-->
<!-- <property name="username" value="root"/>-->
<!-- <property name="password" value="ROOT"/>-->
<!-- 有的配置文件,配置的值就写变量,不写固定的值-->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--配置mybatis的映射文件-->
<mappers>
<mapper resource="dao/UserMapper.xml"></mapper>
</mappers>
</configuration>
5.创建实体类映射文件,并添加进核心配置文件中 UserMapper.xml
<?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="com.xszx.dao.UserMapper">
<insert id="addUser" parameterType="com.xszx.beans.User">
insert into user values (null,#{userName},#{userPwd},#{userRole},null)
</insert>
</mapper>
6.测试
public class UserController {
public static void main(String[] args) throws IOException {
//读取配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//通过配置文件创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//通过sqlSessionFactory创建核心类 sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//通过sqlSession获取dao接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//执行增删改查操作
User user = new User();
user.setUserName("某");
user.setUserPwd("123");
user.setUserRole(1);
userMapper.addUser(user);
//提交sqlSession
sqlSession.commit();
//关闭sqlSession
sqlSession.close();
}
}
Mybatis访问原理
Mybatis基本增删改查操作
XML版本
<?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="com.xszx.dao.UserMapper">
<insert id="addUser" parameterType="com.xszx.beans.User">
insert into user values (null,#{userName},#{userPwd},#{userRole},null)
</insert>
<delete id="delUserId" parameterType="int">
delete from user where userId = #{userId}
</delete>
<update id="updateUser" parameterType="com.xszx.beans.User">
update user set userName=#{userName},userPwd=#{userPwd},userRole=#{userRole} where userId=#{userId}
</update>
<select id="getUsers" resultType="com.xszx.beans.User">
select * from user
</select>
<select id="getUserId" resultType="com.xszx.beans.User">
select * from user where userId=#{userId}
</select>
</mapper>
注解版本
public interface UserMapper {
@Select("select * from user where userId=#{userId}")
User getUserId(int i);
}
使用了注解就不扫描xml文件,但是需要配值mapper接口
参数问题
1.如果方法中参数是自定义对象类型,那么#{}中的属性必须是实体类中的属性
<insert id="addUser" parameterType="com.zx.entity.User">
insert into t_user values (null,#{username},#{password})
</insert>
2.如果方法中的参数是其他类型,那么#{}中的属性不一定是实体类中的属性
3.如果方法中的参数是其他类型,并且有多个参数
方式一:那么dao中的抽象方法中的形式参数前边需要标明注解@Param(“参数名字”)例如:
List<User> getUserByUsernameandid(@Param("id") int id, @Param("username") String username);
<select id="getUserByUsernameandid" resultType="com.zx.entity.User">
select * from t_user where id = #{id} and username = #{username}
</select>
方式二:以param1、param2、…来替换(不推荐)
List<User> getUserByUsernameandid( int id, String username);
<select id="getUserByUsernameandid" resultType="com.zx.entity.User">
select * from t_user where id = #{param1} and username = #{param2}
</select>
参数位置从 0 开始,引用参数语法 #{ arg 位置 } ,第一个参数是#{arg0},第二个是#{arg1}
注:mybatis-3.3 版本和之前的版本使用#{0},#{1}方式,从 mybatis3.4 开始使用#{arg0}方式
方式三:以map集合添加多个参数 #{}中填写map中的key值
HashMap map = new HashMap();
map.put("username","路飞");
map.put("age",23);
List<User> users = userDao.getUserByUsernameandAge(map);
<select id="getUserByUsernameandAge" resultType="com.zx.entity.User" parameterType="map">
select * from t_user where age = #{age} and username = #{username}
</select>
4.SQL注入 ${名称}(通常不用,容易产生sql注入)
<select id="getUserOrderby" resultType="com.zx.entity.User" parameterType="String">
select * from t_user order by ${str} desc
</select>
5.关联对象传参
<select id="getUsersByGid01" resultType="com.zx.entity.User" parameterType="com.zx.entity.User">
select * from t_user where gid = #{group.id}
//select * from t_user where gid = #{role.id}
</select>