mybaits入门
mybatis入门HelloWord
- 废话不说,先来个hellword
- 导入jar包
除了导入mybatis的核心jar包及其依赖包外,还需要导入MySql的驱动jar包
- 定义实体类
省略get,set
public class Student {
private Integer id;
private String name;
private Integer age;
}
- 在数据库中创建实体对应的表
-- Table "student" DDL
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(50) DEFAULT '' COMMENT '名字',
`age` int(11) DEFAULT '0' COMMENT '年龄 ',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='学生表';
- 定义Dao接口
public interface StudentDao {
void insertStudent(Student student) ;
}
- 定义Dao实现类
public class StudentDaoImpl implements StudentDao {
@Override
public void insertStudent(Student student) {
InputStream reader = null;
SqlSession sqlSession = null
try {
// 加载配置xml
reader = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 获取sqlsession
sqlSession = sqlSessionFactory.openSession();
sqlSession.insert("insertStudent",student);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
}finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
}
- mybatis配置文件
- mybaits主配置文件
<?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 resource="jdbc_mysql.properties"/>
<!-- 定义类型别名 -->
<typeAliases>
<!-- <typeAlias type="com.bjpowernode.beans.Student" alias="Student"/> -->
<!-- 将指定包中所有类的简单类名当作其别名 -->
<package name="com.yajun.mybatis.bean"/>
</typeAliases>
<!-- 配置运行环境 -->
<environments default="testEM">
<environment id="testEM">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 注册映射文件 -->
<mappers>
<mapper resource="com/yajun/mybatis/dao/mapper.xml"/>
</mappers>
</configuration>
- 映射文件
<?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="test">
<!-- parameterType属性可以省略 -->
<insert id="insertStudent" parameterType="Student">
insert into student(name,age) values(#{name}, #{age});
</insert>
</mapper>
- 测试类
public class MyTest {
@Test
public void test01() {
Student student = new Student("张三", 16);
StudentDao studentDao = new StudentDaoImpl();
studentDao.insertStudent(student);
}
}
结果:数据库多了一条记录,插入成功
小结:
- 这只是一个helloword,需要优化的肯定有许多。
- 运用mybatis操作数据库的核心,就是获取到sqlSession这个对象,这个对象有对应的api对数据库进行操作。
使用mapper代理改良
使用mybatis的mapper代理不需要dao的实现类
注意点:
- 配置文件的namespace命名必须是接口名的全限定类名。
- 接口的方法名必须和mapper配置文件对应的id一致。
- 通过SqlSession的getMapper()方法创建Dao接口的代理对象。
核心代码实现:
<?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.yajun.mybatis_mapper.dao.StudentDao">
<!-- parameterType属性可以省略 -->
<insert id="insertStudent" parameterType="Student">
insert into student(name,age) values(#{name}, #{age});
</insert>
<update id="updateStudentById" >
update student set name=#{name},age=#{age} where id = #{id}
</update>
</mapper>
public class MyTest {
StudentDao studentDao;
SqlSession sqlSession;
@Before
public void before() {
sqlSession = SqlSessionUtils.getSqlSession();
studentDao = sqlSession.getMapper(StudentDao.class);
}
@After
public void after() {
if (sqlSession != null) {
sqlSession.close();
}
}
@Test
public void test01() {
Student student = new Student("王五", 20);
studentDao.insertStudent(student);
sqlSession.commit();
}
@Test
public void test02() {
Student student = new Student("赵柳", 22);
student.setId(2);
studentDao.updateStudentById(student);
sqlSession.commit();
}
}
mybaits多条件查询问题
- 当有多个条件时,除了可以封装为一个对象外,还可以把参数放到map中
接口: List<Student> selectByCondition(Map<String,Object> map);
xml配置文件:
<select id="selectByCondition" resultType="Student">
select id,name,age from student where `name` like '%' #{name} '%' and age>#{age}
</select>
测试方法:
@Test
public void test03() {
Map<String,Object> map = new HashMap<>();
map.put("name","王");
map.put("age",10);
List<Student> students = studentDao.selectByCondition(map);
System.out.println("11111111");
}
- 多条件查询,还可以放索引:
接口方法:
List<Student> selectByNameAndAge(String name, Integer age);
配置文件:
<select id="selectByNameAndAge" resultType="Student">
select id,name,age from student where `name` like '%' #{0} '%' and age>#{1}
</select>
测试:
@Test
public void test04() {
List<Student> students = studentDao.selectByNameAndAge("王", 10);
for (Student student : students) {
System.out.println(student);
}
}
注意:一定要注意参数的顺序
#{} 中放参数总结
- #{} 中的内容可以放什么内容?
- 参数的对象属性
- 随意内容,此时的#{}是个占位符
- 参数为map时的key
- 参数为map时,若key所对应的value为对象,则可将该对象的属性放入
- 参数的索引号