mybatis-idea之xml方式配置

在idea中使用mybatis
首先创建一个maven的java空项目:
创建maven项目
在pom.xml文件中引入mybatis以及其他需要用到jar包的坐标

<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.25</version>
        </dependency>   
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

mybatis配置文件
在mani目录下的resources下创建一个(名字随意).xml文件。

在这里插入图片描述
database.properties是连接数据库的文件

driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3307/mybits?characterEncoding=utf-8&useSSL=false
username=root
password=513721abcd

在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">

然后进行一些相应的配置

<?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="database.properties"></properties>
    <!--连接数据库文件-->
    <settings>
        <!--开启二级缓存-->
        <setting name="cacheEnabled" value="true"></setting>
        <!--开启延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"></setting>
    </settings>
    <typeAliases>
        <package name="com.tao.domain"></package>
    </typeAliases>
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}" /><!-- ${}中的值要与
				resource中所填的properties文件中的key值相同
				 -->
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--<mapper resource="com/tao/dao/findMapper.xml"></mapper>-->
        <package name="com.tao.dao"></package>
    </mappers>

</configuration>

创意一个对象实体类,再创建一个dao的操作接口用来进行操作,目录如下:
在这里插入图片描述
在findMapper接口中定义一些用来操作数据库的方法

public interface findMapper {

    public List<User> selectAll();

    public User selectById(int id);

    public List<User> selectByName(String name);

    public void insertOne(User user);
    /*
    * 使用封装类作为查询条件
    * */
    public List<User> selectByVo(QueryVo vo);

    public List<User> selectByIds( List<Integer> list);

    public Account selectAccountAndUserById(int id);

    public Account selectAccountById(int id);

    public List<User> selectUserAndAccount();

    public List<Account> selectAccountByOId(int id);

在resources文件夹下创建与findMapper相同目录结构并且名称相同的findMapper.xml文件
在这里插入图片描述
在findMapper.xml中加入mybatis映射文件头

<?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">

紧接着就是对findMapper接口中的方法进行具体操作的配置

<mapper namespace="com.tao.dao.findMapper">

    <cache/><!--配置二级缓存-->

    <!-- 数据库字段名与对象的成员变量不一致 -->
    <resultMap id="user" type="user">

        <id property="id" column="id"></id><!-- 主键-->
        <result property="username" column="username"></result>
        <result property="birthday" column="birthday"></result>
        <result property="sex" column="sex"></result>
        <result property="address" column="address"></result>
    </resultMap>
   <!-- <select id="selectAll" resultType="user">
        select *FROM User
    </select>-->

    <select id="selectAll" resultMap="user" useCache="true"><!--开启二级缓存-->
        select *FROM User
    </select>
    <select id="selectById" parameterType="int" resultType="user">
        select *from User where id= #{id};
    </select>

    <select id="selectByName" parameterType="string" resultMap="user">
        select *FROM User where username  like #{name};
    </select>

    <select id="selectByVo" resultMap="user" parameterType="QueryVo">
        select *FROM User
        <where>
            <if test="user.username!=null">
                and username=#{user.username}
            </if>
            <if test="user.sex!=null">
                and sex=#{user.sex}
            </if>

        </where>
    </select>
    <select id="selectByIds" resultMap="user"><!--parameterType="java.util.List"-->
        select *FROM User
        <where>
            <if test="list!=null and list.size()>0">
            <foreach collection="list" open="id in(" close=")" item="id" separator=",">
                #{id}
            </foreach>
            </if>
        </where>
    </select>

    <resultMap id="accountMap" type="Account">
        <id column="id" property="id"></id>
        <result column="number" property="number"></result>
        <result column="user_id" property="user_id"></result>
        <!-- 一对一关联:column就是根据主表中的此字段查询出从表的数据
         ,在此即根据order表中user_id查询出对应的用户数据。select:填写的是已定义好的
         根据用户id查询用户数据,填写全限定类名加方法名,即用column中的user_id作为id查询
         fetchType:延迟加载或立即加载
         -->
        <association property="user" column="user_id" javaType="user" select="com.tao.dao.findMapper.selectById" fetchType="eager">
            <id column="id" property="id"></id>
            <result property="username" column="username"></result>
            <result property="birthday" column="birthday"></result>
            <result property="sex" column="sex"></result>
            <result property="address" column="address"></result>
        </association>
    </resultMap>
    <select id="selectAccountAndUserById" parameterType="int" resultMap="accountMap">
        SELECT *FROM orders where id=#{id}
    </select>

    <resultMap id="userMap" type="user">
        <!--<id column="id" property="id"></id>
        <result property="username" column="username"></result>
        <result property="birthday" column="birthday"></result>
        <result property="sex" column="sex"></result>
        <result property="address" column="address"></result>-->
        <collection property="accounts" ofType="Account" column="id" select="com.tao.dao.findMapper.selectAccountByOId">
            <!--<id column="id" property="id"></id>
            <result column="number" property="number"></result>
            <result column="user_id" property="user_id"></result>-->
        </collection>
    </resultMap>
    <select id="selectUserAndAccount" resultMap="userMap" >
        select *from User
    </select>

    <select id="selectAccountByOId" parameterType="int" resultType="Account">
        select *FROM orders where user_id=#{id}
    </select>

    <select id="selectAccountById" parameterType="int" resultType="Account">
        select *from orders where id=#{id}
    </select>
    <insert id="insertOne" parameterType="user">
        insert into User(username,birthday,sex,address) values
         (#{username},#{birthday},#{sex},#{address});
        <!-- {}中填入user对象的属性名(get方法去掉get后首字母小写就是属性名) -->

        <!-- 获取自动填入的字段 id -->
         <selectKey keyProperty="id" resultType="int" order="AFTER">
             select last_insert_id();
         </selectKey>
    </insert>
    
</mapper>

最后在Test文件夹下创建一个Tests类进行测试
在这里插入图片描述

public class Tests {

    SqlSession sqlSession=null;
    findMapper mapper=null;
    InputStream inputStream=null;

    @Before
    public void init() throws Exception{
        String resource= "SqlMapConfig.xml";
        inputStream = org.apache.ibatis.io.Resources.getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sessionFactory.openSession();
        mapper = sqlSession.getMapper(findMapper.class);
    }

    @After
    public void close() throws IOException {
        sqlSession.commit();
        sqlSession.close();
        inputStream.close();
    }

    @Test
    public void selectAll() {

        List<User> users = mapper.selectAll();
        for(User user:users){
            System.out.println(user);
        }
    }
}

注意
在配置findMapper.xml文件中

<mapper namespace="com.tao.dao.findMapper">

namespace填写所要进行配置的接口的全限定类名
在mybatis配置文件中 别忘了添加

<mappers>
        <!--<mapper resource="com/tao/dao/findMapper.xml"></mapper>-->
        <package name="com.tao.dao"></package>
    </mappers>

你所要进行配置的接口所在的包名

在mybatis配置文件中进行别名配置

<typeAliases>
        <package name="com.tao.domain"></package>
    </typeAliases>

在填写对象名就不用写全限定类名+对象名,可直接填写对象名,或者如果你在对象上添加了@Alias注解
在这里插入图片描述
此时就填写注解中配置的名称
最后别忘了在创建对象时要实现序列化接口Serializable

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值