MyBatis入门

it2022-05-06  10

目录

MyBatis入门 maven依赖依赖相关的配置 log4j.propertiesmybatis 核心配置user.xml映射查询xmljava类 工具类 SqlSessionFactoryUtils增删改查代码

MyBatis入门

maven依赖

junit 4.11 测试用mysql-connector-java 5.1.17 连接mysqlmybatis 3.2.7 框架log4j 1.2.17 日志记录 <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.17</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.7</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies>

依赖相关的配置

log4j.properties

# Global logging configuration log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

mybatis 核心配置

<?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 resource="jdbc.properties"> <property name="jdbc.username" value="root1"/> <property name="jdbc.password" value="root"/> </properties> <typeAliases> <!-- 单个别名定义,别名的使用,不区分大小写 --> <!-- <typeAlias type="com.itheima.mybatis.pojo.User" alias="user"/> --> <!-- 别名包扫描器:别名是类的全称,不区分大小写,推荐方式 --> <package name="com.itheima.mybatis.pojo"/> </typeAliases> <!-- 和spring整合后 environments配置将废除 --> <environments default="development"> <environment id="development"> <!-- 使用jdbc事务管理 --> <transactionManager type="JDBC" /> <!-- 数据库连接池 --> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </dataSource> </environment> </environments> <!-- 加载映射文件 --> <mappers> <!-- 映射文件包扫描,推荐方式: 1、接口文件必须与映射文件同一目录下 2、接口文件名称必须与映射文件的名称一致 --> <package name="com.itheima.mybatis.mapper"/> </mappers> </configuration>

user.xml映射查询xml

首先创建好User的pojo类(domain/bean)

<?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="user"> <!-- id是之后java中唯一标识 parameterType:之后调用要传回的参数类型 resultType:返回的结果类型(如果是list也是用list中每个单一的元素 变量的使用: #{id} 如果参数类型是普通值,大括号中的变量名可以任意命名 '${value}' 如果参数是String,则一定要用${value},用单引号'',前后可自由增加字符串如'%${value}%' 关于在插入数据中,将自动生成的主键返回给对象的用法 1. <insert (省略id/parameterType) useGeneratedKeys="true" keyProperty="id"> 2. 增加以下语块,赋值是调用mysql中的函数LAST_INSERT_ID(),order表示执行顺序,after为在插入执行完之后再操作,如果是主动设置UUID,则要改为before <selectKey keyProperty="id" resultType="int" order="AFTER"> SELECT LAST_INSERT_ID() </selectKey> --> <select id="getUserById" parameterType="int" resultType="cn.edu.zju.mybaits.pojo.User"> SELECT `id`, `username`, `birthday`, `sex`, `address` FROM `user` WHERE id = #{id} </select> <select id="getUserByUserName" parameterType="string" resultType="cn.edu.zju.mybaits.pojo.User"> SELECT `id`, `username`, `birthday`, `sex`, `address` FROM `user` WHERE username LIKE '%${value}%' </select> <!--插入用户--> <insert id="insertUser" parameterType="cn.edu.zju.mybaits.pojo.User" useGeneratedKeys="true" keyProperty="id"> <!--<selectKey keyProperty="id" resultType="int" order="AFTER">--> <!--SELECT LAST_INSERT_ID()--> <!--</selectKey>--> INSERT INTO `user` (`username`, `birthday`, `sex`, `address` ) VALUES (#{username}, #{birthday}, #{sex}, #{address} ); </insert> <update id="updateUser" parameterType="cn.edu.zju.mybaits.pojo.User"> UPDATE `user` SET `username` = #{username} WHERE `id` = #{id} </update> <delete id="deleteUser" parameterType="int"> DELETE FROM `user` WHERE `id` = #{Id} ; </delete> </mapper>

java类

工具类 SqlSessionFactoryUtils

//不把SqlSession放进来是因为官方推荐SqlSession单独线程 public class SqlSessionFactoryUtils { private static SqlSessionFactory sqlSessionFactory; static { try { //创建SqlSessionFactoryBuilder对象 SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); //创建核心配置文件的输入流 InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); //通过输入流创建SqlSessionFactory对象 sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSessionFactory getSqlSessionFactory() { //sqlSessionFactory单例 return sqlSessionFactory; } }

增删改查代码

public class UserDaoImpl implements UserDao { @Override public User getUserById(Integer id) { SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession(); User user = sqlSession.selectOne("user.getUserById", id); sqlSession.close(); return user; } @Override public List<User> getUserByUserName(String userName) { SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession(); List<User> list = sqlSession.selectList("user.getUserByUserName", userName); sqlSession.close(); return list; } @Override public void insertUser(User user) { /* * SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession() * openSession()里面没写true,则最后要提交事件 sqlSession.commit() */ SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession(true); sqlSession.insert("user.insertUser", user); sqlSession.close(); } }

转载于:https://www.cnblogs.com/richardwlee/p/10455748.html

相关资源:SpringBoot Mybatis 入门 小例子

最新回复(0)