1、在test库创建表student(MySql数据库)
CREATE TABLE ` student` (` id` int(5) NOT NULL AUTO_INCREMENT,
` name` varchar(10) DEFAULT NULL,
` age` int(3) DEFAULT NULL,
` score` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=gbk;
2、创建实体类Student.java
public class Student {
private Integer id; //成员变量【私有的,不暴露给外面】
private String name;
private int age;
private double score;
public Student() {
super();
}
public Student(String name, int age, double score) {
super();
this.name = name;
this.age = age;
this.score = score;
}
public Integer getId() {//属性【暴露给外面的】,方法名可以是getXxx等
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + ", score=" + score + "]";
}
}
3、写Dao接口
public interface IStudentDao {
void insertStudent(Student student); //添加
void insertStudentCacheId(Student student);//添加并返回此学生id
void deleteStudentById(int id);//删除学生
void updateStudentById(Student student);//修改学生
List<Student> selectAllStudents();//查询所有学生,返回List
Map<String, Object> selectAllStudentsMap();//查询所有学生,返回Map
Student selectById(int id);//根据id查询
List<Student> selectByName(String name);//根据name查询
}
4、配置mapper.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="com.xin.mybatis.dao.IStudentDao">
<insert id="insertStudent" parameterType="Student"><!-- mapper动态代理。其底层自动实现Dao接口 -->
insert into student(name,age,score) values(#{name}, #{age}, #{score})
<!-- name是表字段,#{name}这个name是属性,mybatis会自动添加get方法获取属性值,不是成员变量 -->
</insert>
<insert id="insertStudentCacheId" parameterType="Student">
insert into student(name,age,score) values(#{name}, #{age}, #{score})
<!-- mysql:AFTER oracle:BEFORE mysql是先插入后有id -->
<selectKey resultType="int" keyProperty="id" order="AFTER">
select @@identity
</selectKey>
</insert>
<delete id="deleteStudentById">
delete from student where id = #{xxx} <!-- 这块的#{}仅仅是一个占位符,可以随便指定值 -->
</delete>
<update id="updateStudentById" parameterType="Student">
update student set name=#{name},age=#{age},score=#{score} where id=#{id}
</update>
<select id="selectAllStudents" resultType="Student">
select id,name,age,score from student
</select>
<select id="selectById" resultType="Student">
select id,name,age,score from student where id=#{id}
</select>
<select id="selectByName" resultType="Student">
<!-- 推荐使用这种 -->
select id,name,age,score from student where name like '%' #{xxx} '%'
<!-- select id,name,age,score from student where name like concat('%',#{xxx},'%') -->
<!-- 这种不建议使用,这种使用statement查询方式,有sql注入风险 -->
<!-- select id,name,age,score from student where name like '%${value}%' -->
</select>
</mapper>
5、mybatis.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 type="com.xin.mybatis.beans.Student" alias="Student"/> -->
<package name="com.xin.mybatis.beans"/>
</typeAliases>
<!-- 配置环境变量,可以配置多个,有默认值 -->
<environments default="local">
<environment id="local">
<transactionManager type="JDBC" /> <!-- 事务 -->
<dataSource type="POOLED"> <!-- 数据源 连接池POOLED -->
<property name="driver" value="${jdbc.driver.local}"/>
<property name="url" value="${jdbc.url.local}"/>
<property name="username" value="${jdbc.username.local}"/>
<property name="password" value="${jdbc.password.local}"/>
</dataSource>
</environment>
<environment id="online">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 配置映射文件 -->
<mappers>
<mapper resource="com/xin/mybatis/dao/mapper.xml"/>
</mappers>
</configuration>
6、编写jdbc.properties文件
jdbc.driver.local=com.mysql.jdbc.Driver
jdbc.url.local=jdbc:mysql:///test
jdbc.username.local=root
jdbc.password.local=root
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.1.10/online
jdbc.username=query
jdbc.password=xxx
7、编写utils类,用于创建SqlSession
public class MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory;
public static SqlSession getSqlSession() {
try {
InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
if (sqlSessionFactory == null) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //build()方法会把inputStream关闭掉
} else {
inputStream.close();
}
return sqlSessionFactory.openSession();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
8、测试类MyTest.java
public class MyTest {
IStudentDao dao;
SqlSession sqlSession;
@Before
public void before() {
sqlSession = MyBatisUtils.getSqlSession();
dao = sqlSession.getMapper(IStudentDao.class);
}
@After
public void after() {
if (sqlSession != null) {
sqlSession.close();
}
}
@Test
public void test01() {
Student student = new Student("张三", 23, 93.5);
dao.insertStudent(student);
sqlSession.commit();
}
@Test
public void test02() {
Student student = new Student("张三", 23, 93.5);
System.out.println("插入前:" + student);
dao.insertStudentCacheId(student);
sqlSession.commit();
System.out.println("插入后:" + student);
}
@Test
public void test03() {
dao.deleteStudentById(13);
sqlSession.commit();
}
@Test
public void test04() {
Student student = new Student("王五", 25, 95.5);
student.setId(19);
dao.updateStudentById(student);
sqlSession.commit();
}
@Test
public void test05() {
List<Student> students = dao.selectAllStudents();
for (Student student : students) {
System.out.println(student);
}
}
/* @Test
public void test06() {
Map<String, Object> map = dao.selectAllStudentsMap();
System.out.println(map.get("张三"));
}*/
@Test
public void test07() {
Student student = dao.selectById(7);
System.out.println(student);
}
@Test
public void test08() {
List<Student> students = dao.selectByName("张");
for (Student student : students) {
System.out.println(student);
}
}
}
mapper.xml则是与Dao放在相同位置