Mybatis三分钟入门

作者: 业余的猫 | 来源:发表于2017-03-28 20:18 被阅读42次

    1.首先就是配置文件

    <?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>
        <!--  为实体取个别名 -->
        <typeAliases>
            <typeAlias type="类的完全限定名" alias="别名"/>
            <!-- 也可以通过配置包的方式让mybatis自动为该包下的每个类以冠以该类的名称-->
            <package name="com.qfedu.mybatis.entity"/>
        </typeAliases>
        <environments default="development">
            <environment id="development">
                <!-- type可以为MANAGED交给web容器进行管理 -->
                <transactionManager type="JDBC" />
                <!-- 
                    也可以配置JNDI
                < dataSource  type ="JNDI" >
                      < property  name ="DataSource"  value ="java:comp/env/jdbc/myDataSource" />
                </ dataSource > 
              -->
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver" />
                    <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8" />
                    <property name="username" value="root" />
                    <property name="password" value="ily" />
                </dataSource>
            </environment>
        </environments>
        <!-- 配置映射文件 -->
        <mappers>
        <!-- 包级别的路径 -->
        <mapper resource="com/qfedu/mybatis/entity/UserMapper.xml" />
        </mappers>
    </configuration>
    

    2.然后是Mapper

    <?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.qfedu.mybatis.dao.UserDao">
        <!-- 结果映射,如果名字和数据库是意义对应的话可以不用写 id,result等等,但要写的话必须每个字段都要意义对应,且全部都要写 -->
        <resultMap id="UserResult" type="User" >
            <!-- id映射 -->
            <id property="id" column="userId"/>
            <!-- 以下为属性映射 -->
            <result property="username" column="username"/>
            <result property="password" column="password"/>
            <!-- 容器映射 ofType:容器元素的类型,也可以引用另一个resultMap -->
            <collection property="orders" ofType="Order">
                <id property="id" column="orderId"/>
                <result property="time" column="time"/>
                <result property="money" column="money"/>
            </collection>
        </resultMap>
        <!-- 
            以下配置sql语句 parameterType:参数类型, resultType:返回结果类型 #{}:使用和EL表达式差不多 
            例如#{username}相当于parameterType中的username属性
         -->
        <delete id="delete" parameterType="User">
            delete from tb_user where username = #{username}
        </delete>
        <select id="findAllUser" resultMap="UserResult"> 
            select u.*, o.* from tb_user as u left join tb_orders as o on u.userId = o.userId
        </select>
    
        <select id="findById" parameterType="java.lang.Integer" resultType="User">
            select u.*, o.* from tb_user as u, tb_orders as o where u.id = #{id} and u.userId = o.userId
        </select>
        
        <insert id="save" parameterType="User"> 
            insert into tb_user values(default, #{username}, #{password}) 
        </insert>
    </mapper>
    

    3.代码部分

    public class User implements Serializable {
    
        private static final long serialVersionUID = 1L;
        private Integer id;
        private String username;
        private String password;
        private List<Order> orders;
    
        //省略getter和setter
    }
    
    public class Order implements Serializable {
    
        private static final long serialVersionUID = 1L;
        private Integer id;
        private Date time;
        private BigDecimal money;
    
    }
    
    public class Test {
    
        public static void main(String[] args) throws IOException {
            //获取配置文件内容
            InputStream inputStream = Resources.getResourceAsStream("com/qfedu/mybatis/mybatis-config.xml");
            //通过配置文件创建SqlSessionFacroty
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession session = sqlSessionFactory.openSession();
            try {
                UserDao userDao = session.getMapper(UserDao.class);
                List<User> user = userDao.findAllUser();
                session.commit();
            } finally {
                session.close();
            }
        }
    }
    

    总结:在学习mybatis的过程中,有一点特别注意,数据库的主键(一般是id)一定不要相同,加上前缀加以区分,否则mybatis查询时数据会遗漏。

    相关文章

      网友评论

        本文标题:Mybatis三分钟入门

        本文链接:https://www.haomeiwen.com/subject/tuksottx.html