Mybatis01-基本增删改查

1.什么是Mybatis

ORM持久层框架(数据库的增删改查)
1.*/2.*版本叫做ibatis 之后在Google旗下 3.* 改名Mybatis

2.Mybatis和Hibernate的区别

  1. hibernate:是通过实体映射文件将实体类(属性)与表(列)进行,并且能自动生成sql语句
  2. Mybatis 是通过实体映射文件将实体类(属性)与sql语句进行映射,帮我们执行sql语句,并且进行数据的绑定操作

3.创建Maven项目使用Mybatis

  1. 使用Mybatis必然要操作数据库(mysql),在pom文件导入依赖
<dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>5.1.47</version>
	</dependency>
	
	<dependency>
	    <groupId>org.mybatis</groupId>
	    <artifactId>mybatis</artifactId>
	    <version>3.5.6</version>
	</dependency>
  1. 创建实体类
public class Student {
	//需要提供get set 方法这里就不写了
    private Integer sid;
    private String sname;
    private String sex;
    private Integer eid;
}
  1. 提供接口
package com.hr.dao;

import java.util.List;

import com.hr.entity.Student;

public interface StudentMapper {
	//此接口中的方法名必须跟实体映射文件中sql的id一致
	//返回值和参数也要对应
	//实体映射文件的namespace必须与当前接口的全类名一致
	List<Student> selectAll();	
}
  1. 创建资源文件
jdbc.driver=com.mysql.jdbc.Driver //连接驱动信息
jdbc.url=jdbc:mysql://localhost:3306/a6 //连接url
jdbc.username=user //连接账号
jdbc.password=123  //连接密码
  1. 创建Mybatis主配置文件
<?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>
	<!-- 导入db.properties数据库连接信息资源文件 -->
	<properties resource="db.properties"></properties>
	
	<!-- 给实体类取别名,方便实体映射文件中使用 -->
	<typeAliases>
		<!-- 手动给指定实体类取指定别名 -->
		<!-- <typeAlias type="com.hr.entity.UserInfo" alias="user"/> -->
		<!-- 直接给指定包下的类全部取别名,别名就是类名 -->
		<package name="com.hr.entity"/>
	</typeAliases>
	
	<!-- 配置数据库的连接 -->
	<environments default="mysql">
		<environment id="mysql">
			<!-- 配置事物 -->
			<transactionManager type="jdbc"></transactionManager>
			<!-- 配置连接池
			POOLED:使用mybatis提供的连接池
			UNPOOLED:不使用连接池
			JNDI:使用容器提供的连接池
			 -->
			<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>
	
	<!-- 引入实体映射文件 -->
	<mappers>
		<mapper resource="com/hr/entity/Student.xml"/>
	</mappers>
</configuration>
  1. 创建实体映射文件
    Student.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">
<!-- 
namespace:命名空间
作用:避免多实体映射文件时命名的冲突
原则上可以随意赋值,但是建议写成dao层接口的全类名
 -->
<mapper namespace="com.hr.dao.StudentDao">
	<!--标签:
     		select:查询
     		insert:添加
     		delete:删除
     		update:修改
     -->
    <!--
      id:唯一标识
      resultType:返回值类型(Student是取了别名的,没取别就需要全类名)
 	-->
   	<select id="selectAll" resultType="Student">
		select * from Student
	</select>
</mapper>

4.测试接口方法对应配置文件的id

1).测试查询全部的方法

		package com.hr.test;
		import java.io.IOException;
		import java.io.InputStream;
		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 com.hr.mapper.StudentDao;
		public class Test {
			//1.加载mybatis的主配置文件
			InputStream in = Resources.getResourceAsStream("mybatis.xml");
			//2.构建session工厂
			SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(in);
			//3.获取session
			SqlSession session = sf.openSession();
			//4.相关操作
			//通过mybatis用代理的方式自动生成接口的实现类
			StudentDao dao = session.getMapper(StudentDao.class);
			List<Student> list=dao.selectAll();
	 		//5.关session
			session.close();
		}

因为拿session时,重复代码1 2 3 5步基本不变,变的都是4,可以将其封装,提高代码的重用性

2).将构建session工厂封装

		package com.hr.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;
		
		public class BaseSession {
		    private static SqlSessionFactory factory;
		    //访问mybatis读取student数据
		    //1.定义mybatis主配置文件的名称
		    private final static String CONFIG = "mybatis.xml";
		
		    static {
		        //2.读取这个config表示的文件
		        InputStream in = null;
		        try {
		            in = Resources.getResourceAsStream(CONFIG);
		        } catch (IOException e) {
		            e.printStackTrace();
		        }
		        //3.创建了SqlSessionFactoryBuilder对象
		        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
		        //4.创建SqlSessionFactory对象
		        factory = builder.build(in);
		    }
		
		    //获取sqlsession
		    public static SqlSession getSession() {
		        //将参数设置为true:自动提交事务
		        SqlSession sqlSession = factory.openSession(true);
		        return sqlSession;
		    }
		
		    //关闭session
		    public static void closeSession(SqlSession sqlSession) {
		        if (sqlSession != null) {
		            sqlSession.close();
		        }
		    }
		}

3).测试带基本数据类型条件查询的方法

	<!--Student.xml加-->
	<!--注意:
		parameterType的参数int也属于别名  java.lang.Integer 的别名 int 
										 基本数据类型 int 的别名  _int 其他的类似	
		#{}:类似于占位符,可以防止sql注入
	-->
	<select id="selectOne" parameterType="int" resultType="Student">
		select * from Student where sid=#{sid}
	</select>
	//StudentDao接口加
	Student selectOne(int sid);
	//测试
	BaseSession.getSession();
	StudentDao dao = session.getMapper(StudentDao.class);
	Student student=dao.selectOne(1);
	BaseSession.closeSession();

4).测试带实体类条件查询的方法(模糊查询)

	<!--Student.xml加
		参数是实体类对象:#{}中的参数不用关心接口中参数的名字,只关心传进来对象中的属性名
	-->
	<select id="selectOneLike" parameterType="Student" resultType="Student">
		select * from Student where sname like "%" #{sname} "%"
	</select>
	//StudentDao接口加
	Student selectOneLike(Student student);
	//测试
	BaseSession.getSession();
	StudentDao dao = session.getMapper(StudentDao.class);
	Student s=new Student();
	s.setSname("李");
	Student student=dao.selectOneLike(s);
	BaseSession.closeSession();

5).添加

	<!--Student.xml加-->
	<insert id="insert" parameterType="Student" >
        insert into student(sname,sex,eid) value(#{sname},#{sex},#{eid})
    </insert>
	//StudentDao接口加
	int insert(Student student);
	//测试
	BaseSession.getSession();
	StudentDao dao = session.getMapper(StudentDao.class);
	Student s=new Student();
	s.setSname("李");
	s.setSex("男");
	s.setEid(1);
	//返回的影响的行数
	int i =dao.insert(s);
	BaseSession.closeSession();

当添加时,id列是自增长列时,添加成功需要拿到添加的id时,如下 5)

6).添加,拿添加成功的id

	<!--Student.xml加-->
	<!--
		useGeneratedKeys:使用jdbc中提供的getGeneratedKey()的方法获得新添加数据生成的id
		此设置只对有自动编号功能的数据库有效,比如Mysql/SqlServer
		keyColumn:指表中的主键列名
		keyProperty:指实体类中的主键属性名
	-->
	<insert id="insertId" parameterType="Student" 
	useGeneratedKeys="true"  keyColumn="sid" keyProperty="sid" >
        insert into student(sname,sex,eid) value(#{sname},#{sex},#{eid})
    </insert>
	//StudentDao接口加
	int insertId(Student student);
	//测试
	BaseSession.getSession();
	StudentDao dao = session.getMapper(StudentDao.class);
	Student s=new Student();
	s.setSname("李");
	s.setSex("男");
	s.setEid(1);
	//返回的影响的行数
	int i =dao.insertId(s);
	//会将添加成功的id,放入到指定的属性中
	//添加的id
	int id=s.getSid();
	BaseSession.closeSession();

删除 修改:目前没什么注意的

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值