MyBatis的简单使用
Sql
/*
Navicat MySQL Data Transfer
Source Server : Linux_mysql
Source Server Version : 50622
Source Host : 192.168.188.130:3306
Source Database : db_mybatis
Target Server Type : MYSQL
Target Server Version : 50622
File Encoding : 65001
Date: 2019-01-06 18:21:07
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for t_student
-- ----------------------------
DROP TABLE IF EXISTS `t_student`;
CREATE TABLE `t_student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
项目结构
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><!-- 配置根节点 -->
<properties resource="jdbc.properties"/><!-- 属性文件引入 -->
<typeAliases><!-- 实体类关联别名 -->
<typeAlias alias="Student" type="model.Student"/><!-- 设置别名 -->
</typeAliases>
<environments default="development"> <!-- 环境集(默认: 开发者模式) -->
<environment id="development"><!-- 环境(编号: 随便取) -->
<transactionManager type="JDBC" /><!-- 事务管理器 -->
<dataSource type="POOLED"><!-- 数据源(如何连接数据库) -->
<property name="driver" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<mappers><!-- 映射配置 -->
<mapper resource="mappers/StudentMapper.xml" />
</mappers>
</configuration>
jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.188.130:3306/db_mybatis?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root
StudentMapper.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="mappers.StudentMapper">
<!--
#{}: 防注入 ${}:直接拼接,没有双引号
parameterType :参数类型
useGeneratedKeys :是否自动生成主键 keyProperty :主键是哪个属性
-->
<!-- insert -->
<insert id="add" parameterType="Student" useGeneratedKeys="true" keyProperty="id" >
insert into t_student values(null,#{name},#{age})
</insert>
<!-- update -->
<update id="update" parameterType="Student">
update t_student set name = #{name},age = #{age} where id = #{id} and name != #{name}
</update>
<!-- delete -->
<delete id="delete" parameterType = "Integer">
delete from t_student where id = #{id}
</delete>
<delete id="deletes" parameterType = "list">
delete from t_student where id in
<foreach collection="list" item="id" index="index"
open="(" separator="," close=")" >
#{id}
</foreach>
</delete>
<!-- selectAll -->
<select id="selectAll" resultType="model.Student">
select * from t_student
</select>
<!-- selectById -->
<select id="selectById" parameterType="Integer" resultType="model.Student">
select * from t_student where id=#{id}
</select>
<!-- selectWeNa -->
<select id="selectWeNa" parameterType="Student" resultType="model.Student">
select * from t_student where name like #{name} and age=#{age}
</select>
<!-- selectFy -->
<select id="selectFy" parameterType="map" resultType="model.Student">
select * from t_student order by id desc limit #{first},#{end}
</select>
</mapper>
SqlSessionFactoryUtil.java
package util;
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;
public class SqlSessionFactoryUtil {
private static SqlSessionFactory sqlSessionFactory;
public static SqlSessionFactory getSqlSessionFactory(){
if(sqlSessionFactory==null){
InputStream inputStream=null;
try{
inputStream=Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
}catch(Exception e){
e.printStackTrace();
}
}
return sqlSessionFactory;
}
public static SqlSession openSession(){
return getSqlSessionFactory().openSession();
}
}
StudentMapper.java
package mappers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import model.Student;
public interface StudentMapper {
public int add(Student student);
public int update(Student student);
public int delete(Integer id);
public int deletes(ArrayList<Integer> ids);
public List<Student> selectAll();
public List<Student> selectById(Integer id);
public List<Student> selectWeNa(Student student);
public List<Student> selectFy(HashMap<String, Integer> map);
}
Student.java
package model;
public class Student {
private Integer id;
private String name;
private Integer age;
public Student() {
super();
}
public Student(Integer id) {
super();
this.id = id;
}
public Student(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
StudentTest.java
package service;
import java.util.ArrayList;
//底层的
import java.util.HashMap;
//外部的
import org.apache.ibatis.session.SqlSession;
import mappers.StudentMapper;
import model.Student;
import util.SqlSessionFactoryUtil;
public class StudentTest {
public static void main(String[] args) {
SqlSession sqlSession = SqlSessionFactoryUtil.openSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
// 查询所有
// for (Student s : studentMapper.selectAll()) {
// System.out.println(s);
// }
// ID查询
// for (Student s : studentMapper.selectById(1)) {
// System.out.println(s);
// }
// 条件查询
// for (Student s : studentMapper.selectWeNa(new Student("张%", 10))) {
// System.out.println(s);
// }
// 分页查询
// HashMap<String, Integer> map = new HashMap<String, Integer>();
// map.put("first", 0);
// map.put("end", 3);
// for (Student s : studentMapper.selectFy(map)) {
// System.out.println(s);
// }
// 添加
// Student student = new Student("李六", 11);
// int result = studentMapper.add(student);
// System.out.println("相应行数:"+result);
// System.out.println("id:"+student.getId());
// 修改
// Student student = new Student("admin",16);
// student.setId(1);
// int i = studentMapper.update(student);
// System.out.println("成功修改 "+i+" 条数据");
// 删除
// int i = studentMapper.delete(13);
// System.out.println(i==0?"删除失败":"删除成功");
// 批量删除(in)
// ArrayList<Integer> ids = new ArrayList<Integer>();
// ids.add(9);
// ids.add(10);
// ids.add(11);
// int i = studentMapper.deletes(ids);
// System.out.println("删除了 "+i+" 条数据");
sqlSession.commit();
}
}
网友评论