mybatis01

Mybatis

一.创建一个项目的基本步骤

1.搭建环境

1.1使用sql语句创建一个数据库和表

CREATE DATABASE `jcl`;
USE `jcl`;

CREATE TABLE lei_xing (
  id int NOT NULL auto_increment,
  leixing varchar(100),
  PRIMARY KEY (id)
); 

CREATE TABLE dian_ying (
  id int NOT NULL auto_increment,
  leixing_id int DEFAULT NULL,
  ming varchar(100) DEFAULT NULL,
  yanyuan varchar(20) DEFAULT NULL,
  daoyan varchar(20) DEFAULT NULL,
  piaojia float DEFAULT NULL,
  tupianlujing varchar(500) DEFAULT NULL,
  PRIMARY KEY (id), 
  CONSTRAINT dian_ying_ibfk_1 FOREIGN KEY (leixing_id) REFERENCES lei_xing (id)
) ; 


insert into lei_xing(id,leixing) values (1,'动画');
insert into lei_xing(id,leixing) values (2,'动作');
insert into lei_xing(id,leixing) values (3,'爱情');
insert into lei_xing(id,leixing) values (4,'喜剧');
insert into lei_xing(id,leixing) values (5,'惊悚');
insert into lei_xing(id,leixing) values (6,'3D');
insert into lei_xing(id,leixing) values (7,'其它');

insert into dian_ying(id,leixing_id,ming,yanyuan,daoyan,piaojia) values (1,1,'哪吒','哪吒','不知道',100);
insert into dian_ying(id,leixing_id,ming,yanyuan,daoyan,piaojia) values (2,2,'复仇者联盟4','唐尼','我',20);
insert into dian_ying(id,leixing_id,ming,yanyuan,daoyan,piaojia) values (3,3,'呵呵','哈哈','怀藏族',22);
insert into dian_ying(id,leixing_id,ming,yanyuan,daoyan,piaojia) values (4,1,'魔童降世','申公豹','姜太公',10);
insert into dian_ying(id,leixing_id,ming,yanyuan,daoyan,piaojia) values (5,4,'魔童降世2','申公豹','姜太公',20);
insert into dian_ying(id,leixing_id,ming,yanyuan,daoyan,piaojia) values (6,3,'魔童降世3','姜子牙','菩提祖师',30);
insert into dian_ying(id,leixing_id,ming,yanyuan,daoyan,piaojia) values (7,3,'魔童降世4','姜子牙','菩提祖师他姐',40);

1.2创建maven项目

​ 创建maven项目,删除src,导入maven jar包

<dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      <scope>testscope>
    dependency>

    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.5.9version>
    dependency>

    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>8.0.25version>
    dependency>

    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-apiartifactId>
      <version>1.7.5version>
    dependency>

    <dependency>
      <groupId>log4jgroupId>
      <artifactId>log4jartifactId>
      <version>1.2.17version>
    dependency>
    
  dependencies>

1.3创建一个模块

编写mybatis的配置文件



<configuration>







    <environments default="xxx">
        <environment id="xxx">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/film?serverTimezone=Asia/Shanghai"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            dataSource>
        environment>
    environments>

    <mappers>
        <mapper resource="mapper/LeiXingMapper.xml">mapper>
    mappers>
configuration>
编写mybitsUtils工具类
package com.jcl.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

//mybatis工具类
public class mybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            String resource = "org/mybatis/example/mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch(IOException e){
            e.printStackTrace();
        }
    }

//    通过SqlSessionFactory的opensession()方法来获取SqlSession
    public static SqlSession getSqlSession(){
        return  sqlSessionFactory.openSession();
    }
}

1.4编写代码

实体类

package com.study.entity;

public class LeiXing {
    /*
    *   id
    *   leiXing
    */
    private Integer id;//int 不可以表示null,而包装类可以
    private String leiXing;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLeiXing() {
        return leiXing;
    }

    public void setLeiXing(String leiXing) {
        this.leiXing = leiXing;
    }

    @Override
    public String toString() {
        return "LeiXing{" +
                "id=" + id +
                ", leiXing='" + leiXing + '\'' +
                '}';
    }
}

Dao接口

public interface LeiXingMapper {
    List<LeiXing> getLeiXingList();
}

接口实现类 (由原来的UserDaoImpl转换为一个Mapper配置文件)






<mapper namespace="com.jcl.dao.LeiXingMapper">


    <select id="getLeiXingList" resultType="com.jcl.pojo.LeiXing">
    select * from lei_xing
  select>
mapper>

1.5测试

junit测试

Q:

  • build配置resource中存在资源导出失败的问题
  • 配置文件的注册
  • 方法名不同
  • 返回类型不对
  • maven导出资源问题
package com.jcl.dao;

import com.jcl.pojo.LeiXing;
import com.jcl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class LeiXingMapperTest {
    @Test
    public void test(){
//    z    1.获取sqlsession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
//        2.执行SQL
//        sqlSession.getMapper从LeiXingMapper.class得到了leiXingMapper对象,在调用对象的方法
        LeiXingMapper leiXingMapper = sqlSession.getMapper(LeiXingMapper.class);
        List<LeiXing> list = leiXingMapper.getLeiXingList();
        for (LeiXing leiXing : list) {
            System.out.println(leiXing);
        }

//        3.关闭Session
        sqlSession.close();
    }
}

二.CRUD

接口,mapper.xml Test

1、namespace

namespace中的包名要和Dao/mapper接口的包名一致!

2、select

查询语句;

id:对应namespace中的方法名

resultType:Sql语句执行的返回值!

parameterType:参数类型

3、insert

useGeneratedKeys 取得自增的id值,返回到keyproperty所设置的属性中

public interface LeiXingMapper {
    //获取全部的类型数据
    List<LeiXing> getLeiXingList();
    //根据id查询类型
    LeiXing getLeiXingById(int id);
    //插入一个类型
    void addLeiXing(LeiXing leiXing);
    //修改一个类型
    void updateLeiXing(LeiXing leiXing);
    //删除一个类型
    void deleteLeiXing(int id);
}
 	<select id="getLeiXingById" resultType="com.jcl.pojo.LeiXing" parameterType="int">
    select * from lei_xing where id = #{id}
 	select>
    <insert id="addLeiXing" parameterType="com.jcl.pojo.LeiXing">
        insert into lei_xing(id,leixing)values(#{id},#{leixing})
    insert>
    <update id="updateLeiXing" parameterType="com.jcl.pojo.LeiXing">
        update lei_xing set leixing=#{leixing}  where id=#{id};
    update>
    <delete id="deleteLeiXing" parameterType="int">
        delete from lei_xing where id = #{id}
    delete>
public class LeiXingMapperTest {
    @Test
    public void getLeiXingListTest(){
//        1.获取sqlsession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
//        2.执行SQL
//        sqlSession.getMapper从LeiXingMapper.class得到了leiXingMapper对象,在调用对象的方法
        LeiXingMapper leiXingMapper = sqlSession.getMapper(LeiXingMapper.class);
        List<LeiXing> list = leiXingMapper.getLeiXingList();
        for (LeiXing leiXing : list) {
            System.out.println(leiXing.toString());
        }

//        3.关闭Session
        sqlSession.close();
    }
    @Test
    public void getLeiXingByIdTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        LeiXingMapper leiXingMapper = sqlSession.getMapper(LeiXingMapper.class);
        LeiXing leiXing = leiXingMapper.getLeiXingById(1);
        System.out.println(leiXing);
        sqlSession.close();
    }
    @Test
    public void  addLeiXingTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        LeiXingMapper leiXingMapper = sqlSession.getMapper(LeiXingMapper.class);
        leiXingMapper.addLeiXing(new LeiXing(666,"jcl"));
//        提交事物
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void updateLeiXingTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        LeiXingMapper leiXingMapper = sqlSession.getMapper(LeiXingMapper.class);
        leiXingMapper.updateLeiXing(new LeiXing(666,"jclnb"));
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void deleteLeiXingTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        LeiXingMapper leiXingMapper = sqlSession.getMapper(LeiXingMapper.class);
        leiXingMapper.deleteLeiXing(666);
        sqlSession.commit();
        sqlSession.close();
    }
}

3、增删查改是要提交事物
sqlSession.commit();

2.1Map

假设实体类参数过多,或者数据库中的表,字段,或者参数过多,要考虑使用map

你可能感兴趣的:(SSM,学习,java)