MyBatis的基本用法

一:MyBatis的体系结构

    MyBatis的持久化解决方案将用户从原始的JDBC访问中解放出来,用户只需要定义需要操作的SQL语句,无需关注底层的JDBC操作,就可以以面向对象的方式进行持久化操作。底层数据库连接的获取、数据库访问的实现、事务控制等都无需用户关心。

    MyBatis常用的两个对象:SqlSessionFactory和SqlSession。

    SqlSessionFactory:单个数据库映射关系经过编译后的内存镜像。线程安全,是SqlSession的工厂。

    SqlSession:执行持久化操作的对象,应用程序与持久存储层之间交互操作的一个单线程对象,SqlSession对象完全包含以数据库为背景的所有执行SQL操作的方法,底层封装了JDBC连接,可以使用SqlSession实例直接执行以映射的SQL语句。

二:实例

   1、 测试select、insert、update、delete操作:

一:配置mybatis-config.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>
    <!--指定mybatis所用日志的具体实现-->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <!--设置别名-->
    <typeAliases>
        <typeAlias type="com.jiaotong.pojo.User" alias="user"/>
    </typeAliases>
    <!--环境配置 连接的数据库-->
    <environments default="mysql">
        <environment id="mysql">
            <!--指定事务管理类型 type=JDBC 使用JDBC的提交和回滚设置-->
            <transactionManager type="JDBC"></transactionManager>
            <!--dataSource 指数据源配置 POOLED 是JDBC连接对象的数据源连接池的实现 -->
            <dataSource type="POOLED">
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="12345" />
                <property name="driver" value="com.mysql.jdbc.Driver" />
            </dataSource>
        </environment>
    </environments>
    <!--mappers告诉Mybatis去哪里找持久化类的映射文件-->
    <mappers>
        <mapper resource="com/jiaotong/mapper/UserMapper.xml"/>
        <mapper resource="com/jiaotong/mapper/ItemList.xml"/>
    </mappers>
</configuration>

二:编写mapper

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.jiaotong.mapper.UserMapper">
    <insert id="saveUser" parameterType="user" useGeneratedKeys="true">
        INSERT INTO TB_USER(NAME ,SEX,AGE) VALUES(#{name},#{sex},#{age})
    </insert>
    <select id="selectUser" parameterType="int" resultType="user">
        SELECT * FROM TB_USER WHERE id = #{id}
    </select>
    <update id="modifyUser" parameterType="user">
        UPDATE TB_USER
        SET name =#{name}, sex=#{sex},age=#{age}
        where id=#{id}
    </update>
    <delete id="deleteUser" parameterType="int">
        DELETE FROM TB_USER WHERE id=#{id}
    </delete>
</mapper>


三:测试

    1、插入测试

public class InsertTest {
    public static void main(String args[]){
        SqlSession sqlSession = FKSqlSessionFactory.getSqlSession();
        User user = new User("Tim","男",2);
        sqlSession.insert("com.jiaotong.mapper.UserMapper.saveUser",user);
        sqlSession.commit();
        sqlSession.close();
    }
}
    2、查询测试
public class SelectTest {
    public static void main(String args[]){
        SqlSession sqlSession = FKSqlSessionFactory.getSqlSession();
        User user = sqlSession.selectOne("com.jiaotong.mapper.UserMapper.selectUser",3);
        sqlSession.commit();
        System.out.println(user.getName()+" "+user.getId());
        sqlSession.close();
    }
}

    3、更新测试

public class UpdateTest {
    public static void main(String args[]){
        SqlSession sqlSession = FKSqlSessionFactory.getSqlSession();
        /**1 将对象查到*/
        User user = sqlSession.selectOne("com.jiaotong.mapper.UserMapper.selectUser",3);
        user.setAge(18);
        user.setName("大王");
        /**2 更新*/
        sqlSession.update("com.jiaotong.mapper.UserMapper.modifyUser",user);
        sqlSession.commit();
        sqlSession.close();
    }
}
    4、删除测试
public class DeleteTest {
    public static void main(String args[]){
        SqlSession sqlSession = FKSqlSessionFactory.getSqlSession();
        sqlSession.delete("com.jiaotong.mapper.UserMapper.deleteUser",3);
        sqlSession.commit();

        sqlSession.close();
    }
}

为了方便的获得SqlSession对象,写了一个工具类:

public class FKSqlSessionFactory {
    private static SqlSessionFactory sqlSessionFactory = null;
   static {
       try{
           InputStream inputStream = Resources.getResourceAsStream("mybatis/mybatis-config.xml");
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
       }catch(Exception e){
           e.printStackTrace();
       }
   }
   public static SqlSession getSqlSession(){
       return sqlSessionFactory.openSession();
   }
   public static SqlSessionFactory getSqlSessionFactory(){
       return sqlSessionFactory;
   }
}

    2、实例    测试ResultMaps

        resultMap元素是mybatis最重要的元素,告诉mybatis将从结果集中取出的数据转换成开发者所需要的对象。

    1、建立班级和学生表

CREATE TABLE TB_CLAZZ(
id INT PRIMARY KEY AUTO_INCREMENT,
CODE varchar(18)
);
INSERT into TB_CLAZZ(CODE) VALUES('J1601');
INSERT into TB_CLAZZ(CODE) VALUES('J1602');

CREATE TABLE TB_STUDENT(
id int PRIMARY key AUTO_INCREMENT,
NAME VARCHAR(18),
sex CHAR(18),
age INT,
clazz_id int,
FOREIGN KEY(clazz_id) REFERENCES TB_CLAZZ(id)
);

INSERT INTO TB_STUDENT(NAME,sex,age,clazz_id) VALUES('jack','男',22,1);
INSERT INTO TB_STUDENT(NAME,sex,age,clazz_id) VALUES('Tom','女',22,1);
INSERT INTO TB_STUDENT(NAME,sex,age,clazz_id) VALUES('Lucy','女',22,2);
INSERT INTO TB_STUDENT(NAME,sex,age,clazz_id) VALUES('Nacy','男',22,2);

 2、建立pojo对象    

public class Clazz {
    private Integer id;
    private String code;
    //省略get set
}
public class Student {
    private Integer id;
    private String name;
    private String sex;
    private Integer age;
    private Clazz clazz;}

   3、写mapper映射文件

    查询所有学生信息

<!--映射学生对象的ResultMap-->
    <resultMap id="studentResultMap" type="com.jiaotong.pojo.Student">
        <id property="id" column="id"></id>
        <result property="name" column="name"/>
        <result property="sex" column="sex"/>
        <result property="age" column="age"/>
        <!--关联映射-->
        <association property="clazz" column="clazz_id" javaType="com.jiaotong.pojo.Clazz" select="selectClazzWithId"/>
    </resultMap>
    <!--根据id查询班级-->
    <select id="selectClazzWithId" resultType="com.jiaotong.pojo.Clazz">
        SELECT * FROM TB_CLAZZ where id =#{id}
    </select>
    <!--查询学生的所有信息-->
    <select id="selectStudent" resultMap="studentResultMap">
        SELECT * FROM TB_STUDENT
    </select>

    查询所有的班级信息

    

public class Clazz {
    private Integer id;
    private String code;

    private List<Student> students;
}

<!--映射班级对象的ResultMap-->
    <resultMap id="clazzResultMap" type="com.jiaotong.pojo.Clazz">
        <id property="id" column="id"></id>
        <result property="code" column="code"></result>
        <collection property="students" javaType="ArrayList" column="id" ofType="com.jiaotong.pojo.Student"
        select="selectStudentWithId"></collection>
    </resultMap>
    <select id="selectStudentWithId" resultType="com.jiaotong.pojo.Student">
        SELECT * FROM TB_STUDENT WHERE clazz_id =#{id}
    </select>
    <!--查询所有的班级信息-->
    <select id="selectClazz" resultMap="clazzResultMap">
        SELECT * FROM TB_CLAZZ
    </select>

4、测试

       

public class SelectStudentTest {

	public static void main(String[] args) throws Exception {
		// 获得Session实例
		SqlSession session = FKSqlSessionFactory.getSqlSession();
		// 查询TB_USER表所有数据返回List集合,集合中的每个元素都是一个Student对象
		List<Student> student_list
			= session.selectList("com.jiaotong.mapper.UserMapper.selectStudent");
		// 遍历List集合,打印每一个Student对象,该对象包含关联的Clazz对象
		for(Student stu : student_list){
			System.out.println(stu);
		}
		// 提交事务
		session.commit();
		// 关闭Session
		session.close();
	}

}
    
public class SelectClazzTest {

	public static void main(String[] args) throws Exception {
		// 获得Session实例
		SqlSession session = FKSqlSessionFactory.getSqlSession();
		// 查询TB_CLAZZ表所有数据返回List集合,集合中的每个元素都是一个Clazz对象
		List<Clazz> clazz_list
			= session.selectList("com.jiaotong.mapper.UserMapper.selectClazz");
		// 遍历List集合,打印每一个Clazz对象和该Clazz关联的所有Student对象
		for(Clazz clazz : clazz_list){
			System.out.println(clazz);
			List<Student> student_list = clazz.getStudents();
			for(Student stu : student_list){
				System.out.println(stu.getId() + " " + stu.getName() + " " + stu.getSex() + " " + stu.getAge());
			}
		}
		// 提交事务
		session.commit();
		// 关闭Session
		session.close();
	}

}





  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis Plus 是一个 MyBatis 的增强工具,在 MyBatis 的基础上添加了许多实用的功能,可以极大地提高 MyBatis 的开发效率。 MyBatis Plus 的基本使用方法如下: 1. 引入 MyBatis Plus 的依赖 Maven 依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> ``` 2. 配置 MyBatis Plus 在 Spring Boot 的配置文件中添加 MyBatis Plus 的配置,如下: ```yaml mybatis-plus: # 实体扫描,多个用逗号分隔 typeAliasesPackage: com.example.demo.entity # mapper 扫描,多个用逗号分隔 mapperLocations: classpath:/mapper/*.xml # 配置数据库驱动、连接地址、用户名和密码 global-config: db-config: id-type: auto table-prefix: t_ ``` 3. 编写实体类 ```java @Data @AllArgsConstructor @NoArgsConstructor public class User { private Long id; private String name; private Integer age; private String email; } ``` 4. 编写 Mapper ```java @Mapper public interface UserMapper extends BaseMapper<User> { } ``` 5. 使用 MyBatis Plus 提供的 API ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> getUserList() { return userMapper.selectList(null); } @Override public User getUserById(Long id) { return userMapper.selectById(id); } @Override public boolean addUser(User user) { return userMapper.insert(user) > 0; } @Override public boolean updateUser(User user) { return userMapper.updateById(user) > 0; } @Override public boolean deleteUser(Long id) { return userMapper.deleteById(id) > 0; } } ``` 以上就是 MyBatis Plus 的基本使用方法,通过 MyBatis Plus 提供的 API,我们可以很方便地进行 CRUD 操作。同时,MyBatis Plus 还提供了很多其他的实用功能,例如分页查询、条件查询、乐观锁、自动填充等等,可以根据具体需求进行使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值