一个简单的MyBatis程序实例
2018-01-12 22:30
495 查看
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); } } }
配置文件默认都在类路径下面,即src文件夹下。
mapper.xml则是与Dao放在相同位置
相关文章推荐
- 【Qt5开发及实例】19、一个简单的画图程序
- struts2入门-第一个例子==》第一个struts2实例——HelloWorld==》Struts2.0搭建和简单实例==>写一个Steuts2的经典入门案例,做了一个登陆程序作为入门例子
- Android之蓝牙 一个简单实用的Android蓝牙程序实例
- UNIX-LINUX编程实践教程->第八章->实例代码注解->写一个简单的shell->在shell中启动另一个程序
- 一个简单的MyBatis程序
- 一个简单的SWT程序实例及详解-Java基础-Java-编程开发
- delphi程序只允许运行一个实例的简单方法:
- 一个简单的python程序实例(通讯录)
- MFC 程序最小化到系统托盘区的一个简单实例 .
- 一个简单实用的Android蓝牙程序实例
- 使用事件处理创建一个简单的绘图实例程序 python
- 一个简单的linux下网络程序实例-网络编程入门 收藏
- 本文实现了一个基于servlet技术的简单的csv文件导出的程序实例。
- ADA程序实例(一个简单的智能指针实现)
- 【MyBatis学习01】一个简单入门实例
- C语言经典实例008:一个简单的求和程序
- C++ 容器的综合应用的一个简单实例——文本查询程序
- 一个简单的SWT程序实例及详解(转)
- ADA程序实例(一个简单的智能指针实现)
- C#一个简单下载程序实例(可用于更新)