mybatis学习(二)

                                                                                          mybatis几大对象的生命周期,以及简单的crud

一、mybatis几大对象的生命周期

1、SqlSessionFactryBuilder :这个对象只是用于创建SqlSessionFatory,只要 SqlSessionFactory创建成功,则自动销毁

2、SqlSessionFactory:整个应用执行期间都一直存在;通常使用单例形式

3、sqlSession: 每一个线程都应该有单独的独立的sqlSession ,相互之间不受影响,必 须保证每一个SqlSession是一个线程独立拥有的,所以我们一般都是在finally中关    闭;否则可能导致内存溢出

二、MybatisMapper.xml文件的标签(selectinsertupdatedelete)上的属性,以下仅列举了常用的:

id :为命名空间唯一标示,可以用来引用该对应标签下的sql语句

parameterType :定义该标签下sql语句中传入的参数对应的类名或者权限定名

resultType:数据库查询出的数据封装成期望对象的权限定名或者别名,如果为集合,则是集合中元素类型

statementType:可以拥有3个值(STATEMENTPREPAREDCALLABLE),对应jdbc中特殊的语句类

                           STATEMENT:最简单的sql,就是直接在等号右边写具体值的

                           PREPARED:预编译的sql通常是一占位符传参的方式

                           CALLABLE:通常指调用存储过程的形式等复杂处理  

flushCache:为是否缓存标签下的sql模板,如果为true每次执行都会清除该模板sql,为fasle则把sql模板缓存起来,默认false

timeout:超时,定义驱动程序等待数据库放回请求结果,如果时间超过指定值,则抛 出异常

userGeneratedKeys:仅仅对insert有效,使用自动生成的键,会让mybatis调用 getGeneratedKes方法取出数据新增的id,仅针对数据库的主键有自增功能方                  可使用

 

三、别名的设置

在我们parameterType resultType这两个属性中,我们可以设置传入或者返回对象类型,一般情况我们都是用权限定类名,但是权限定类名过于复杂,我们就可以设置别名

别名的标签<typeAliases></typeAliases> <typeAlias/>

方式如下:

<typeAliases>

       <typeAlias alias="别名" type="对应类的全类名"/>

</typeAliases>

 

例如:

Mapper中原来的配置:

<update id="updateEmployee"                parameterType="cn.ycj.mybatis.domain.Employee">

      update Employee set name=#{name},password=#{password} where id=#{id}

   </update>

配置别名

<typeAliases>

         <typeAlias  alias="Employee"  type="cn.ycj.mybatis.domain.Employee"/>

   </typeAliases>

 

配置别名后的配置

<update id="updateEmployee"             parameterType="Employee">

      update Employee set name=#{name},password=#{password} where id=#{id}

   </update>

  

    

四、 Mybatis使用步骤:

1、加载配置文件,创建SqlSessionFactory

2.、获取会话 SqlSession

3、操作以及提交事务

4、关闭会话

 

五、做一个EmployeeCRUD

1、创建一个Employee类,提供相应的构造方法和getter settertoString方法

publicclass Employee {

   private Long id;

   private String name;

   private String password;

   public Employee() {

      super();

   }

   public Employee(String name, String password) {

      super();

      this.name = name;

      this.password = password;

   }

   public Long getId() {

      returnid;

   }

   publicvoid setId(Long id) {

      this.id = id;

   }

   public String getName() {

      returnname;

   }

   publicvoid setName(String name) {

      this.name = name;

   }

   public String getPassword() {

      returnpassword;

   }

   publicvoid setPassword(String password) {

      this.password = password;

   }

   @Override

   public String toString() {

      return"Employee [id=" + id + ", name=" + name + ", password="

            + password + "]";

   }

  

  

}

2、创建mybatis的配置文件mybatis-config.xmlEmployee的映射文件EmployeeMapper文件,mapper中先为空白,做一个加一个配置文件

mybatis-config.xml内容:

<configuration>

   <typeAliases>

      <typeAlias  alias="Employee" type="cn.ycj.mybatis.domain.Employee"/>

   </typeAliases>

   <environments default="development">

      <environment id="development">

         <transactionManager type="JDBC" />

         <dataSource type="POOLED">

            <property name="driver" value="com.mysql.jdbc.Driver" />

            <property name="url" value="jdbc:mysql://localhost:3306/mybatis?createDatabaseIfNotExist=true" />

            <property name="username" value="root" />

            <property name="password" value="admin" />

         </dataSource>

      </environment>

   </environments>

   <mappers>

      <mapper resource="cn/ycj/mybatis/domain/EmployeeMapper.xml" />

   </mappers>

</configuration>

 

 

 

EmployeeMapper.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="org.mybatis.example.EmployeeMapper">

  

</mapper>

 

3、创建一个junitEmployeeDao测试类,先为空白,做一个方法加一个方法

package cn.ycj.mybatis.dao;

publicclass EmployeeDaoTest {

  

}

 

 

4、做一个单例模式的mybatis的工具

SqlSessionFactoryBuilderSqlSessionFactory整个活动中只需要使用一个,所以可以创建一个静态类来获取一个通用的,但是session不能是通用,故提供一个获取session的方法,每次都获得新的session,类如下:

publicclass MybatisUtils {

   privatestatic SqlSessionFactory sessionFactory;

   static {

      try {

         Reader reader = Resources.getResourceAsReader("mybatis-config.xml");

         sessionFactory = new SqlSessionFactoryBuilder().build(reader);

      } catch (IOException e) {

         e.printStackTrace();

      }

   }

   publicstatic SqlSession getSession() {

      returnsessionFactory.openSession();

   }

}

 

 

5、mysql(大家可以是用自己常用的数据库),建立employee

6、执行添加数据操作

在配置文件中做一条插入数据的配置

<insert id="insertEmp" parameterType="Employee" >

      insert into employee(name,password) values(#{name},#{password})

   </insert>

传入的时一个Emloyee对象,设置的时候对字段则为#{Employee对应的属性}

EmployeeDao中写测试代码执行操作

@Test

   publicvoid save() throws Exception {

      SqlSession session = MybatisUtils.getSession();

      Employee emp=new Employee("yc", "222");

      session.insert("insertEmp", emp);

      session.commit();

      session.close();

   }

这里可以发现,用openSession()打开的session的事物需要自己手动提交

 

7、查询一条数据

Mapper文件添加如下配置,记得做Employee的别名

<select id="selectEmp" parameterType="Long" resultType="Employee">

      select * from Employee where id=#{id}

   </select>

EmployeeDao中写测试代码执行操作

@Test

   publicvoid get() throws Exception {

      SqlSession session = MybatisUtils.getSession();

      Employee emp=session.selectOne("selectEmp", 2L);//这里不用强转换,mybatis会自动封装

session.close();

      System.out.println(emp);

   }

 

 

 

8、查询所有数据

Mapper文件添加如下配置,

<select id="findAll" resultType="Employee">

         select * from Employee

   </select>

EmployeeDao中写测试代码执行操作  

@Test

   publicvoid getAll() throws Exception {

      SqlSession session = MybatisUtils.getSession();

      List<Employee> emps=session.selectList("findAll");//这里不用强转换,mybatis会自动封装

      session.close();

      System.out.println(emps);

   }

 

9、删除一条数据

 

Mapper文件添加如下配置,

<delete id="deleteEmp" parameterType="Long">

      delete from employee where id=#{id};

   </delete>

 

EmployeeDao中写测试代码执行操作

@Test

   publicvoid delete() throws Exception {

      SqlSession session = MybatisUtils.getSession();

      session.delete("deleteEmp",2L);

      session.commit();

      session.close();

  

   }

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值