mybatis入门案例及基础配置

mybatis入门案例及基础配置

一、pom.xml配置
<!--打包方式-->
 <packaging>jar</packaging>
 <!--主要依赖-->
 <dependencies>
         <!--添加mybatis jar包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
         <!--添加mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
         <!--//日志文件依赖jar包 log4j-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <!--测试jar包-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>


    </dependencies>
二 、SqlMapConfig.xml配置(resoures根目录下)
配置属性properties
配置别名tybeAlias
配置通用设置setting
配置数据库环境
配置加载映射配置文件
1.复制内容 (在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">
2.配置内容

<configuration>
<!--引入jdbc
此处jdbcConfig.properties内容
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123-->

    <properties resource="jdbcConfig.properties"/>
    <!--开启延迟加载-->
    <settings>
 <!--<setting name="aggressiveLazyLoading" value="false"/>   3.4.1以上可以不写-->
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>
      <!--开启二级缓存-->
         <setting name="cacheEnabled" value="true"/><!--value默认值为true-->
    <!--别名设置-->
    <typeAliases>
        <package name="com.it.domin"></package>
    </typeAliases>
    <!-- 配置环境 -->
    <environments default="mysql">
        <!--配置MySQL环境 -->
        <environment id="mysql">
            <!--配置事务类型 -->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置数据源(连接池) -->
            <dataSource type="POOLED">
                <!--配置连接数据库的4个基本信息 -->
                <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>

    <!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
    <mappers>
        <!--<mapper resource="com/it/dao/IUserDao.xml"/>-->
              <package name="com.it.dao"/>
    </mappers>
</configuration>
三、接口xml配置

(配置文件的全限定类名必须与其配置的接口的全限定类名完全一致:如接口 com.it.IUserDao 则 com.it.IUserDao.xml)

1.复制部分
<!--复制部分-->
<?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">
2.配置内容
<!--namespace属性写配置接口的全限定类名-->
<!--parameterType属性填写参数类型-->
<mapper namespace="com.it.dao.IUserDao">
<!-- 配置查询所有 id必须为所调用方法名 在resultType中可以使用全限定类名也可以使用别名,即不区分大小写的类名:user-->
    <select id="findAll" resultType="com.it.domin.User">
        SELECT * FROM  user;
    </select>

<!-- 添加用户 id必须为所调用方法名 在resultType中可以使用全限定类名也可以使用别名,即不区分大小写的类名-->
    <insert id="saveUser" parameterType="com.it.domin.User">
        <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
            SELECT last_insert_id();
        </selectKey>
        INSERT INTO user VALUES (null,#{username},#{birthday},#{sex},#{address})
    </insert>

<!-- 删除用户 id必须为所调用方法名 在resultType中可以使用全限定类名也可以使用别名,即不区分大小写的类名-->
    <delete id="deleteUser" parameterType="int">
        DELETE FROM user where id=#{uid};
    </delete>

<!-- 修改用户 id必须为所调用方法名 在resultType中可以使用全限定类名也可以使用别名,即不区分大小写的类名-->
    <update id="updateUser" parameterType="com.it.domin.User" >
            UPDATE user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id}
    </update>
<!-- 模糊查询 id必须为所调用方法名 在resultType中可以使用全限定类名也可以使用别名,即不区分大小写的类名-->
    <select id="findByLike" parameterType="String" resultType="com.it.domin.User">
        SELECT * FROM user where username like #{username};
    </select>
<!-- 单个查询 id必须为所调用方法名 在resultType中可以使用全限定类名也可以使用别名,即不区分大小写的类名-->
    <select id="findOne" parameterType="int" resultType="com.it.domin.User">
        SELECT * FROM  user where id = #{id};
    </select>
</mapper>
四、测试类
public class MybatisTest {
    private InputStream in;
    private SqlSession session;
    private IUserDao userDaoproxy;

    @Before
    public void init() throws Exception {
  //1.读取配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
  //2.创建SqlSessionFactory工厂
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
  //3.使用工厂生产SqlSession对象,在openSession()方法中传入一个true参数则自动开启提交事务
        session = factory.openSession();
        //4.使用SqlSession创建Dao接口的代理对象
        userDaoproxy = session.getMapper(IUserDao.class);
    }

    @After
    public void end() throws Exception {
        //提交事务
        session.commit();
        //6.释放资源
        in.close();
        session.close();
    }
     /**
     * 入门案例
     *
     * @param
     */
    @Test
    public void find() {
        //5.使用代理对象执行方法
        List<User> users = userDaoproxy.findAll();
        for (User user : users) {
            System.out.println(user);
        }
    }
    
}

mybatis中一对一查询及相应配置

一、接口xml配置
<!--IAcountDao.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.it.dao.IAcountDao">
    <!--结果集映射 -->
    <!--resultMap id即取了别名方便下面其他语句调用,type在主配置文件中配置了别名可不写全限定类名,而写类名,property填类中属性名,column指数据库表中列名-->
    <resultMap id="accountResultMap" type="acountUser">
        <id column="id" property="id"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
<!--一对一使用association标签 此处property填上类的属性名 JavaType填此此属性的类型 column在此处填写表中列名-->
        <association property="user" column="id"  javaType="user">
            <id column="id" property="id"></id>
            <result property="username" column="username"/>
            <result property="sex" column="sex"/>
            <result property="address" column="address"/>
            <result property="birthday" column="birthday"/>
        </association>
    </resultMap>
    <!--select标签中id为调用方法名,此处应使用结果集resultMap为返回值类型-->
    <select id="findAll" resultMap="accountResultMap">
      select a.id id,a.uid uid,a.money,u.* from user u,account a where u.id=uid;
    </select>
</mapper>
二、测试类
public class MybatisTest {
    private InputStream in;
    private SqlSession session;
    private IAcountDao userDaoproxy;

    @Before
    public void init() throws Exception {
        //1.读取配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.使用工厂生产SqlSession对象
        session = factory.openSession();
        //4.使用SqlSession创建Dao接口的代理对象
        userDaoproxy = session.getMapper(IAcountDao.class);
    }

    @After
    public void end() throws Exception {
        //提交事务
        session.commit();
        //6.释放资源
        in.close();
        session.close();
    }
 @Test
    public void findAcountUser(){
     List<AcountUser> users = userDaoproxy.findAll();
     for (AcountUser a:users) {
         System.out.println(a);
     }
}

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.it.dao.IUserDao">
    <!-- 配置查询所有-->
     <resultMap id="userAcount" type="user">
         <id property="id" column="uid"></id>
         <result property="username" column="username"></result>
         <result property="sex" column="sex"></result>
         <result property="birthday" column="birthday"></result>
         <result property="address" column="address"></result>
         <!--一对多,多对多采用collection标签 property属性填写相应类中属性 类型用oftype属性-->
         <collection property="acountUsers" ofType="acountUser">
             <id property="id" column="aid" ></id>
             <result property="uid" column="uid"></result>
             <result property="money" column="money"></result>
         </collection>
     </resultMap>
    <!--开启二级缓存-->
       <cache/>
    <select id="findAll" resultMap="userAcount">
        SELECT u.*,a.id aid,a.money,a.uid FROM user u LEFT OUTER JOIN account a on u.id=a.uid
    </select>
</mapper>
二、测试类
public class MybatisTest {
    private InputStream in;
    private SqlSession session;
    private IUserDao dao;

    @Before
    public void init() throws Exception {
        //1.读取配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.使用工厂生产SqlSession对象
        session = factory.openSession();
        //4.使用SqlSession创建Dao接口的代理对象
         dao = session.getMapper(IUserDao.class);
    }

    @After
    public void end() throws Exception {
        //提交事务
        session.commit();
        //6.释放资源
        in.close();
        session.close();
    }

    @Test
    public void findUserAcount(){
          List<User> users = dao.findAll();
         for (User a:users) {
             System.out.println(a);
             System.out.println(a.getAcountUsers() );
         }
     }
 }

mybatis中多对多查询及相应配置

一、接口xml配置
<!--IRoleDao-->
<?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.it.dao.IRoleDao">
    <!-- 配置查询所有-->
     <resultMap id="userAcount" type="role">
         <id property="roleId" column="rid" ></id>
         <result property="roleName" column="role_Name"></result>
         <result property="roleDesc" column="role_Desc"></result>
         <collection property="users" ofType="user">
             <id property="id" column="id"></id>
             <result property="username" column="username"></result>
             <result property="sex" column="sex"></result>
             <result property="birthday" column="birthday"></result>
             <result property="address" column="address"></result>
         </collection>
     </resultMap>
    <select id="findAll" resultMap="userAcount">
        SELECT r.id rid,r.role_name,r.role_desc,u.* FROM  role r  
        LEFT OUTER JOIN user_role ur on ur.rid=rid LEFT OUTER JOIN user u on  u.id=ur.uid
    </select>
</mapper>
<!--IUserDao-->
<?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.it.dao.IUserDao">
    <!-- 配置查询所有-->
     <resultMap id="userAcount" type="user">
         <id property="id" column="id"></id>
         <result property="username" column="username"></result>
         <result property="sex" column="sex"></result>
         <result property="birthday" column="birthday"></result>
         <result property="address" column="address"></result>
         <collection property="roles" ofType="role">
             <id property="roleId" column="rid" ></id>
             <result property="roleName" column="role_Name"></result>
             <result property="roleDesc" column="role_Desc"></result>
         </collection>
     </resultMap>
    <select id="findAll" resultMap="userAcount">
        SELECT u.*,r.id rid,r.role_name,r.role_desc FROM user u LEFT OUTER JOIN user_role ur on u.id=ur.uid LEFT OUTER JOIN role r on ur.rid=rid
    </select>
</mapper>
二、测试类
public class MybatisTest {
    private InputStream in;
    private SqlSession session;
    private IUserDao dao;
    private IRoleDao roleDao;

    @Before
    public void init() throws Exception {
        //1.读取配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.使用工厂生产SqlSession对象
        session = factory.openSession();
        //4.使用SqlSession创建Dao接口的代理对象
         dao = session.getMapper(IUserDao.class);
         roleDao=session.getMapper(IRoleDao.class);
    }

    @After
    public void end() throws Exception {
        //提交事务
        session.commit();
        //6.释放资源
        in.close();
        session.close();
    }
 @Test
    public void findUserAll(){
     List<User> users = dao.findAll();
     for (User a:users) {
         System.out.println(a);
     }
 }
 @Test
    public void findRoleAll(){
     List<Role> users = roleDao.findAll();
     for (Role a:users) {
         System.out.println(a);
     }
 }
}

mybatis注解中一对一查询及相应配置

一、一对一接口的注解
public interface IAcountDao {
     @Select("select * from account")  
    /*@Results注解中id属性为别名,写了在后续可以引用,如果类中属性名和列名不一样 value中可以写对应别名如:
     @Resulet(property="类中属性名",cloumn="表中列名")
     ...
    最后写一对一格式
     one=@One(select="全限定类名加方法名" fetchType=FetchType.EAGER为立即加载 LAZY为延迟加载)
    */
    @Results(id="acountUser",value = {
         @Result(property = "user",column = "uid",one=@One(select =                              "com.it.dao.IUserDao.findById",fetchType = FetchType.EAGER))
    })
    List<AcountUser> findAll();

    @Select("select * from account where account.uid=#{id}")
    List<AcountUser> findById(Integer id);
    
    @Select("select count(*) from account where account.uid=#{id}")
    int findByIdTotal(int id);
}
1.2一对多接口注解
public interface IUserDao {

    @Select("select * from user ")
    @Results(id = "userMap" ,value={
        @Result(property = "acountUsers",column = "id",many = @Many(select =    "com.it.dao.IAcountDao.findById",fetchType = FetchType.LAZY))
        })
    List<User> findAll();
    
    @Select("select * from user where user.id=#{id}")
    @ResultMap("userMap")
    User findById(Integer id);

}
二、测试类
public class MybatisTest {
    private InputStream in;
    private SqlSession session;
    private IAcountDao userDaoproxy;
    private IUserDao dao;

    @Before
    public void init() throws Exception {
        //1.读取配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.使用工厂生产SqlSession对象
        session = factory.openSession();
        //4.使用SqlSession创建Dao接口的代理对象
        userDaoproxy = session.getMapper(IAcountDao.class);
         dao = session.getMapper(IUserDao.class);
    }

    @After
    public void end() throws Exception {
        //提交事务
        session.commit();
        //6.释放资源
        in.close();
        session.close();
    }
    @Test
    public void findAcountUser(){
     List<User> users = dao.findAll();

     for (User a:users) {
         System.out.println(a);
         System.out.println(a.getAcountUsers());
         }
     }

    @Test
    public void findByTotal(){
     int byIdTotal = userDaoproxy.findByIdTotal(41);
     System.out.println(byIdTotal);
    }

    @Test
    public void findUser(){
     List<AcountUser> users = userDaoproxy.findAll();
     for (AcountUser a:users) {
         System.out.println(a);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值