mybatis入门

1.mybatis概述

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所 有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原 始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录

持久化:就是瞬时数据(比如内存中的数据,是不能永久保存的)持久化为持久数据(比如持久化至数据库中,能够长久保存)。dao层:DAO (Data Access Object) 数据访问对象,简单来说就是操作数据库的!

2.快速启动mybatis

2.1创建一个数据库并插入一些数据

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xDI6UbXr-1660286192111)(C:\Users\huang\AppData\Roaming\Typora\typora-user-images\image-20220811163602482.png)]

2.2创建一个maven工程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SHdIIHFG-1660286192112)(C:\Users\huang\AppData\Roaming\Typora\typora-user-images\image-20220811164132602.png)]

2.3导入工程依赖

https://mvnrepository.com可以直接在这个网站上搜索 (注意每次修改完pom文件后要刷新

  		  <packaging>jar</packaging>
    <dependencies>
        <!--mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <!--lombok依赖 自动帮我们生成get\set方法-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>
        <!--c3p0连接池-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
    </dependencies>

2.4配置mybatis-config.xml

在resource目录下新建一个mybatis-config.xml文件和db.properties

<?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="db.properties"/>
    <environments default="development">
        <!--      development这套环境  -->
        <environment id="development">
            <!--            事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <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>
</configuration>

2.5编写连接数据库的工具类

 //SqlSession的工厂,也是mybatis的核心
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //读取配置文件
            InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
            //构建sqlSessionFactory工厂对象
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取SQL Session对象,等价于jdbc的连接
    public static SqlSession getSession(){
        return sqlSessionFactory.openSession(true);//true自动提交事务
    }

2.6搭建所需要的包及类

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pkhDptVP-1660286192113)(C:\Users\huang\AppData\Roaming\Typora\typora-user-images\image-20220811172221683.png)]

user类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private Integer id;
    private String username;
    private String passwd;
    private String sex;
}

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="com.hq.hml.mapper.UserMapper">

</mapper>
2.7查询所有
 //查询所有
    List<User> selectAll();
 <!--为了和将实体类的属性和数据库的字段相对应-->
<!--配置文件中namespace中的名称为对应Mapper接口或者Dao接口的全限定名,必须一致!-->
    <resultMap id="map" type="com.hq.hml.entity.User">
        <id property="id" column="id"/>
        <result column="username" property="username"/>
        <result property="passwd" column="passwd"/>
        <result column="sex" property="sex"/>
    </resultMap>
    <!--查询-->
<select id="selectAll" resultMap="map">
    select * from test_ifo
</select>
@Test
public void testSelectAll(){
    //得到session对象
    SqlSession session = MybatisUtils.getSession();
    //反射获取mapper接口
    UserMapper mapper = session.getMapper(UserMapper.class);
    //遍历
    List<User> list = mapper.selectAll();
    for (User user : list) {
        System.out.println(user);
    }
}
2.8添加一条数据
//添加
Integer insertOne(User user);
    <!--添加-->
<insert id="insertOne">
    insert into test_ifo values (#{id},#{username},#{passwd},#{sex})
</insert>
//添加
@Test
public void testInsertOne(){
    //得到session对象
    SqlSession session = MybatisUtils.getSession();
    //反射获取mapper接口
    UserMapper mapper = session.getMapper(UserMapper.class);
    int i=mapper.insertOne(new User(null,"黄明亮","123","男"));
    System.out.println(i>0 ? true :false);
}
2.9删除一条数据
//删除
Integer deleteOneById(Integer id);
    <!--删除-->
<delete id="deleteOneById">
    delete from test_ifo where id=#{id}
</delete>
//删除
@Test
public void testDeleteById(){
    //得到session对象
    SqlSession session = MybatisUtils.getSession();
    //反射获取mapper接口
    UserMapper mapper = session.getMapper(UserMapper.class);
    Integer i = mapper.deleteOneById(3);
    System.out.println(i>0 ? true : false);
}
2.10修改数据
//修改
Integer updateUser(User user);
    <!--修改-->
<update id="updateUser" >
    update test_ifo set id=#{id},username=#{username},passwd=#{passwd},sex=#{sex} where id=#{id}
</update>
//修改
@Test
public void updateUser(){
    //得到session对象
    SqlSession session = MybatisUtils.getSession();
    //反射获取mapper接口
    UserMapper mapper = session.getMapper(UserMapper.class);
    Integer i = mapper.updateUser(new User(11, "黄明亮", "love", "男"));
    System.out.println(i>0 ? true : false);

}
2.11通过id查询
//通过id查询
User selectUserById(Integer id);
<!--通过id查询-->
<select id="selectUserById" resultMap="map">
    select * from test_ifo where id=#{id}
</select>
@Test
public void  testSelectUserById(){
    SqlSession session = MybatisUtils.getSession();
    UserMapper mapper = session.getMapper(UserMapper.class);
    User user = mapper.selectUserById(11);
    System.out.println(user);
}

3.日志实现

<settings> 

<setting name="logImpl" value="STDOUT_LOGGING"/> 

</settings> 

Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、

GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等;我们也可以控制每一条日志

的输出格式;通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。最令人感兴趣的就

是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

3.1添加日志依赖

(如果版本不可用可以换版本 https://mvnrepository.com)

<!-- 日志实现--> 
<dependency> 
<groupId>log4j</groupId> 
<artifactId>log4j</artifactId> 
<version>1.2.17</version>
</dependency>

3.2编写log.propertites文件

(不唯一可以自己在网上找)

#将等级为DEBUG的日志信息输出到console和file这两个目的地
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/User.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别 Log4j建议只使用四个级别,优先级从高到低分别是ERROR、WARN、INFO、DEBUG。
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

4.注解开发

使用注解开发不需要用到mapper.xml文件

  @Select("select * from test_ifo")
    List<User> selectAll();

    @Select("select * from test_ifo where id=#{id}")
    User selectById(Integer id);

    @Delete("delete from test_ifo where id=#{id}")
    Integer deleteById(Integer id);

    @Insert("insert into test_ifo values(#{id},#{username},#{passwd},#{sex})")
    Integer insertOne(User user);

    @Update("update test_ifo set id=#{id},username=#{username},passwd=#{passwd},sex=#{sex} where id=#{id}")
    Integer updateOne(User user);

测试方法和上面的一样

5.动态sql

动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同

条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名

的逗号。利用动态 SQL,可以彻底摆脱这种痛苦

5.1if

if标签,使用test属性进行逻辑判断,如果条件满足 ,保留标签体中的内容

如果条件不满足,不保留标签体中的内容

5.2set

<!-- set标签 帮助我们动态处理sql update操作中set子语句 会自动帮我们处理结尾处多出的逗号(,) --> 
   update user
        <set>
        <if test="userId != null and userId !='' ">
        user_id=#{userId},
        </if>
        <if test="name != null and name !='' ">
        name=#{name},
        </if>
        <if test="sex != null and sex !='' ">
        sex=#{sex},
        </if>
        <if test="address != null and address !='' ">
        address=#{address},
        </if>
        <if test="phone != null and phone !='' ">
        phone=#{phone},
        </if>
        <if test="email != null and email !='' ">
        email=#{email},
        </if>
        <if test="username != null and username !='' ">
        username=#{username},
        </if>
        <if test="password != null and password !='' ">
        password=#{password},
        </if>
        <if test="deleted != null and deleted !='' ">
        deleted=#{deleted}
        </if>
    </set>
        where user_id=#{userId}

         </update>

5.3where标签

<!-- where标签 动态的生成where子句,主要和if标签搭配使用 帮助我们处理where子句中 靠近where关键字的 and 和 or sql关键字 当标签体中有内容时,生成where关键字,没有内容时,不会生成where关键字 -->
   <select id="selectUserById" resultMap="userMap1">
        select * from user
        <where>
            <if test="userId!=null and userId!='' ">
            user_id=#{userId}
            </if>
        </where>
    </select>

5.4foreach标签

<!-- foreach 循环控制 collection属性指定要遍历的集合变量 item属性指定循环变量,自行命名,在标签体中使用#{}引用其值 使用open属性来指定循环开始之前要拼接的内容 使用close属性来指定循环结束要拼接的内容 使用separator属性来指定循环中要拼接的内容 --> 
<select id="querySomeByIds" resultType="User"> 
		select <include refid="userColumnSql" /> from user
		<foreach collection="ids" item="id" open="where user_id in (" close=")" separator=","> 	
            ${id}
</foreach> 
</select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值