Mabitis

Mybatis

一、框架概念:

Java框架,一个软件半成品,简单来说就是一个别人搭好的舞台,你来做表演,说白了Java框架就是封装好方便程序员操作的类,使项目的开发更简单,维护起来也更容易。

而Mybatis框架是一个优秀的java持久层框架,他内部封装了jdbc,开发者只需要关注sql语句本身,其他繁琐的操作框架会替你完成。

二、入门:

1.开发dao:

1.1 原始dao开发模式

编写dao接口,编写dao实现类,存在大量重复代码!

1.2使用mapper代理开发模式(推荐):

1.2.1配置xml:

*SqlMapConfig.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 resource="jdbc.properties"/>
    <!--配置环境-->
    <environments default="mysql">
        <!--配置mysql的环境-->
        <environment id="mysql">
            <!--配置事务的类型-->
            <transactionManager type="JDBC"/>
            <!--配置数据源《连接池》-->
            <dataSource type="POOLED">
                <property name="driver" value="${DriverClassName}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
     <mappers>
         <mapper resource="Usermapper.xml"/>
     </mappers>
</configuration>

*userMapper.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="cn.zzz.dao.Usermapper">
    <!--    配置方法,后面的为表面查询封装返回处-->
    <select id="findAll" resultType="cn.zzz.domain.User">
        select *from user
     </select>

    <!--  parameterType是对应的mapper接口方法接受的参数类型  -->
    <insert id="saveUser" parameterType="cn.zzz.domain.User" useGeneratedKeys="true" keyProperty="id">
    insert into user(username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{addrsss});
    </insert>

    <update id="updateUser" parameterType="cn.zzz.domain.User">
    update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
    </update>

    <delete id="deleteUser" parameterType="Integer">
        delete from user where id = #{userid}
    </delete>
</mapper>

*jdbc.properties配置:

	DriverClassName=com.mysql.jdbc.Driver
	url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
	username=root
	password=******
	initialSize=5
	maxActice=10
	maxWait=3000

*测试方法:

public class MybatisTest {
    private InputStream in;
    private SqlSession session;
    private Usermapper usermapper;

    @Before
    public void init() throws Exception{
         in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlsessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3.使用工厂生产SqlSession对象
         session = factory.openSession();
        //4.使用SqlSession创建Dao接口的代理对象
        usermapper = session.getMapper(Usermapper.class);
    }

    @After
    public void destory()throws Exception{
        session.close();;
        in.close();
    }

     @Test
     public void findAllTest() throws Exception {
            //5.使用代理对象执行方法
        List<User> users = usermapper.findAll();
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void saveUser(){
        User user = new User();
        user.setUsername("3241");
        user.setBirthday(new Date());
        user.setSex("男");
        user.setAddrsss("1231241");

        usermapper.saveUser(user);

        session.commit();
        System.out.println(user);
    }


    @Test
    public void updateUser(){
        User user = new User();
        user.setId(53);
        user.setUsername("155");
        user.setBirthday(new Date());
        user.setSex("男");
        user.setAddrsss("544");

        usermapper.updateUser(user);

        session.commit();
    }

    @Test
    public void deleteUser(){
        User user = new User();

        usermapper.deleteUser(49);
        session.commit();
    }
}

1.2.2注意事项:

*我的mysql安装为8.0,所以在url后面要加上 “?useUnicode=true&characterEncoding=utf8”

*主键回填:
一般id是主键,我们在插入信息时也不必主动去设置。数据库会自动增长,但插入成功后我们要得知插入数据的id是多少时,就得设置这2个:

useGeneratedKeys="true" keyProperty="id" 仅能在或者< update>元素中使用,作用是获取自增主键的id
例:

@Test
public void saveUser(){
    User user = new User();
    user.setUsername("3241");
    user.setBirthday(new Date());
    user.setSex("男");
    user.setAddrsss("1231241");

    usermapper.saveUser(user);

    session.commit();
    System.out.println(user);
}

没有加上时:打印出来的id为null,反之。

2.连接池

在SqlMapConfig.xml中配置:

1.POOLED:使用数据库连接池


2.UNPOOLED:不使用数据库连接池

3.JNDI

3.动态sql语句

where+if语句:

<select id="findUserbyCondition" resultType="cn.zzz.domain.User">
    select *from user
    <where>
        <if test="username!=null">
            and username = #{username}
        </if>
    </where>
</select>



@Test
public void findUserbyCondition() throws Exception {
    User user = new User();
    user.setUsername("老王");
    //5.使用代理对象执行方法
    List<User> users = usermapper.findUserbyCondition(user);
    for (User user1 : users) {
        System.out.println(user1);
    }
}


查询结果:
User{id=41, username='老王', birthday=Tue Feb 27 17:47:08 CST 2018, sex='男', addrsss='null'}
User{id=46, username='老王', birthday=Wed Mar 07 17:37:26 CST 2018, sex='男', addrsss='null'}

where+foreach:

 <select id="findUserbyCondition" resultType="cn.zzz.domain.User">
    select *from user
    <where>
        id in 
        <foreach collection="list" open="(" close=")" separator="," item="id" >
            #{id}
        </foreach>
    </where>
</select>



public void findUserbyCondition() throws Exception {
   List<Integer> list = new ArrayList<Integer>();
   list.add(41);
   list.add(42);
   List<User> users = usermapper.findUserbyCondition(list);
    for (User user : users) {
        System.out.println(user);
    }

}

查询结果:
User{id=41, username='老王', birthday=Tue Feb 27 17:47:08 CST 2018, sex='男', addrsss='null'}
User{id=42, username='小二王', birthday=Fri Mar 02 15:09:37 CST 2018, sex='女', addrsss='null'}

3.映射

一对一:

user类:

public class User {
    private String username;
    private String sex;

 //以下省略get和set、toString方法

order类:

public class Order  {
    private int id;
    private int userid;
    private String number;

    private User user;

	//以下省略get和set、toString方法

OrderMapper.xml:

<mapper namespace="cn.zzz.dao.OrderMapper">
<resultMap id="orderMap" type="cn.zzz.domain.Order">
    <id property="id" column="oid"></id>
    <result property="userid" column="userid"></result>
    <result property="number" column="number"></result>
    <association property="user" javaType="cn.zzz.domain.User">
        <result property="username" column="username"></result>
        <result property="sex" column="sex"></result>
    </association>
</resultMap>

<select id="findAll" resultMap="orderMap">
  select u.*, o.id,o.userid,o.number from `order` o,`user` u where o.userid =u.id;
</select>

运行结果:

Order{id=1, userid=1, number='10000', user=User{username='是谁', id=1, sex='男'}}
Order{id=2, userid=5, number='11111', user=User{username='解开了', id=5, sex='男'}}
Order{id=3, userid=2, number='13431', user=User{username='老王', id=2, sex='男'}}
Order{id=4, userid=3, number='131231', user=User{username='哦哦', id=3, sex='女'}}

注意事项:
数据库的order表和user表的id最好不要相同,否则Mabatis会弄混,导致这样结果:

Order{id=1, userid=1, number='10000', user=User{username='是谁', id=1, sex='男'}}
Order{id=5, userid=5, number='11111', user=User{username='解开了', id=5, sex='男'}}
Order{id=2, userid=2, number='13431', user=User{username='老王', id=2, sex='男'}}
Order{id=3, userid=3, number='131231', user=User{username='哦哦', id=3, sex='女'}}
即order的id强制跟user的id相同

一对多:

Class类:

	public class Class  {
   		 private Integer id;
   		 private String name;
   		 private List<Student> students;
	}

Student类:

public class Student {
    private Integer id;
    private String name;
    private String sex;
    private Integer age;

}

ClassMapper.xml:

<mapper namespace="cn.zzz.dao.ClassMapper">

<resultMap id="classMap" type="cn.zzz.domain.Class">
    <id property="id" column="c_id"/>
    <result property="name" column="c_name"/>
    <collection property="students" ofType="cn.zzz.domain.Student">
        <id property="id" column="s_id"/>
        <id property="name" column="s_name"/>
        <id property="age" column="s_age"/>
        <id property="sex" column="s_sex"/>
    </collection>
</resultMap>
<select id="findAll" resultMap="classMap">
    select s.*, c.* from tb_student s, tb_class c where s.s_c_id = c.c_id;
</select>

三.注解开发

CURD

使用注解开发便不需要mapper.xml这样的配置文件了

*下面是代码:

userMapper:

public interface UserMapper  {

    @Select("select *from user")
    List<User> findAll();

    @Insert("insert into user(username,sex) value(#{username},#{sex})")
    void SaveUser(User user);

    @Update("update user set username=#{username}, sex=#{sex} where id =#{id}")
    void updateUser(User user);

    @Delete("delete from user where id =#{id}")
    void deleteUser(int id);
}

SqlMapConfig相关改动:

 <mappers>
        <mapper class="cn.zzz.dao.UserMapper"/>
 </mappers>

一对一:

user表:

id	username	sex
1	是谁			男
2	老王			男
4	123			男
5	解开了		男
6	王二			女

user:

 private int id;
 private String username;
 private Order order;
 getter and setter 方法
 toString 方法

order表:

id	 userid  	 number	
1	  1		  	 10000
2	  5		   	 11111
3	  2			 13431
4	  3			 131231

order:

private int oid;
private int userid;
private String number;

OrderMapper:

public interface OrderMapper {

    @Select("select *from `order` where userid = #{id} ")
    Order findOrderById(int id);
}

Usermapper:

public interface UserMapper  {

    @Select("select *from user")
    @Results({
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "username",property = "username"),
            @Result(column = "sex",property = "sex"),
            @Result(column = "id",property = "order",one = @One(select = "cn.zzz.dao.OrderMapper.findOrderById",fetchType = FetchType.EAGER))
    })
    List<User> findAll();
}

查询结果:

User{id=1, username='是谁', order=Order{oid=1, userid=1, number='10000', user=null}, sex='男'}
User{id=2, username='老王', order=Order{oid=3, userid=2, number='13431', user=null}, sex='男'}
User{id=4, username='123', order=null, sex='男'}
User{id=5, username='解开了', order=Order{oid=2, userid=5, number='11111', user=null}, sex='男'}
User{id=6, username='王二', order=null, sex='女'}

一对多和多对多:大致相同

posted @ 2020-01-30 20:45  喜欢悠哉独自在✘  阅读(73)  评论(0编辑  收藏