MyBatis的使用
1.使用maven引入依赖:
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.4</version> </dependency>
2.在resources目录下编写主配置文件(mybasit.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配置文件 --> <properties resource="db.properties"></properties> <!-- environments 主要用于进行数据源的配置 可以配置多个数据源~ 通过default属性来指定当前项目运行过程中使用的是哪个数据源 --> <environments default="development"> <!-- environment 用于配置一个具体的独立的数据源 id属性用于给当前数据源定义一个名称,方便我们的项目指定 --> <environment id="development"> <!-- transactionManager用于配置事务管理,默认情况下使用的是JDBC事务管理 --> <transactionManager type="JDBC"/> <!-- dataSource具体数据源的链接信息;type属性用于指定是否使用连接池 --> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> <environment id="product"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> <environment id="test"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <!-- mappers主要用于配置我们外部的映射配置文件 在主配置文件中需要引入加载映射配置文件 --> <mappers> <!-- mapper主要配置引入某一个具体的映射文件,resource进行路径方式的引入 --> <mapper resource="mapper/usersMapper.xml"/> </mappers> </configuration>
2.1.编写工具类:
package com.damu.utils; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; /** * Created by mouwe on 2017/5/23. */ public class SqlSessionFactoryUtils { private static String RESOURCE = "mybatis-config.xml"; private static SqlSessionFactory sqlSessionFactory; private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>(); /** * 创建一个初始化SqlSessionFactory的方法 */ public static void initSqlSessionFactry() { try { InputStream is = Resources.getResourceAsStream(RESOURCE); sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); } catch (IOException e) { e.printStackTrace(); } } /** * 获取工厂对象的方法 * @return */ public static SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } /** * 关闭SqlSession的方法 */ public static void close(){ SqlSession session = threadLocal.get(); if(session != null) { session.close(); threadLocal.set(null); } } }
3.配置db.properties:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
username=root
password=root
4.配置映射配置文件(增删改查):
<?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属性是用来配置命名空间,主要进行session级别的缓存管理 命名空间默认情况下,使用我们当前操作的实体类的全路径 --> <mapper namespace="com.damu.entity.Users"> <!--<select id="findUsers" resultType="com.damu.entity.Users">--> <select id="findUsers" resultMap="forUsers"> select * from users <if test="id != null"> where id = #{id} </if> </select> <!-- 自定义映射关系集合:主要包含对于一些自定义操作的配置,如不一致的属性和字段 --> <resultMap id="forUsers" type="com.damu.entity.Users"> <!-- 绑定id主键 --> <id property="id" column="id"></id> <!-- result配置,主要配置普通属性,column表示配置的是数据库字段名称 property配置的是实体类的属性名称 --> <result column="username" property="name"></result> <collection property="addresses" column="id" ofType="com.damu.entity.Address" select="getAddress"></collection> </resultMap> <select id="getAddress" resultType="com.damu.entity.Address"> select * from address where userid = #{id} </select> <sql id="user_fields"> username, userpass, nickname, age, gender, email, phone, createTime, updateTime, lastLogin, userstatus, remark </sql> <insert id="addUser" useGeneratedKeys="true" keyProperty="id"> insert into users( <include refid="user_fields"></include>) values(#{name},#{userpass}, #{nickname}, #{age}, #{gender}, #{email}, #{phone}, #{createTime}, #{updateTime}, #{lastLogin}, #{userStatus}, #{remark}) </insert> <update id="updateUser"> update users <set> <if test="name != null">username = #{name},</if> <if test="userpass != null">userpass = #{userpass},</if> <if test="nickname != null">nickname = #{nickname},</if> <if test="age != null">age = #{age},</if> <if test="gender != null">gender = #{gender},</if> <if test="email != null">email = #{email},</if> <if test="phone != null">phone = #{phone},</if> <if test="createTime != null">createTime = #{createTime},</if> <if test="updateTime != null">updateTime = #{updateTime},</if> <if test="lastLogin != null">lastlogin = #{lastLogin},</if> <if test="userStatus != null">userStatus = #{userStatus},</if> <if test="remark != null">remark = #{remark},</if> </set> where id = #{id} </update> <delete id="delUser"> delete from users where id = #{id} </delete> </mapper>
5.通过Dao类与数据库建立会话(增删改的操作记得使用commit()提交数据,不然不能生效):
package com.damu.dao; import com.damu.entity.Users; import com.damu.utils.SqlSessionFactoryUtils; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import java.util.List; /** * Created by mouwe on 2017/5/23. */ public class UsersDAO { private SqlSession sqlSession; private List<Users> list; private Users user; private SqlSession getSession() { sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession(); return sqlSession; } /** * 查询全部用户 * @return */ public List<Users> findAll() { try { list = getSession().selectList("findUsers"); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } return list; } /** * 查询单个用户根据编号 * @return */ public Users findById(Integer id) { try { user = getSession().selectOne("findUsers", new Users(id)); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } return user; } /** * 增加一个新用户数据到数据库的方法 * @return */ public Users addUser(Users user) { try { // 返回值:是insert执行过程中影响的行数 getSession().insert("addUser", user); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } return user; } /** * 用于修改用户资料的方法 * @return */ public Users updateUsers(Users user) { try { // 返回值:是insert执行过程中影响的行数 getSession().update("updateUser", user); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } return user; } /** * 用于修改用户资料的方法 * @return */ public void delUsers(Integer id) { try { // 返回值:是insert执行过程中影响的行数 getSession().delete("delUser", id); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } } }
<!---使用的数据库连接池 ---->