首页 > 代码库 > MyBatis-增删改查
MyBatis-增删改查
1.创建Maven项目,项目名称mybatisdemo1,目录结构如图所示
2.pom.xml中配置内容如下
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mycompany</groupId> <artifactId>mybatisdemo1</artifactId> <version>0.0.1-SNAPSHOT</version> <build/> <dependencies> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.39</version> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> </dependencies> </project>
3.在src/main/java目录创建实体类StudentBean,包名(com.mycompany.beans),目录结构如下
4.实体类StudentBean的内容如下
package com.mycompany.beans; public class StudentBean { private Integer sid; private String name; public StudentBean() { super(); } public StudentBean(String name) { super(); this.name = name; } public StudentBean(Integer sid, String name) { super(); this.sid = sid; this.name = name; } public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return "StudentBean [sid="+sid+",name="+name+"]"; } }
5.在src/main/java下创建接口StudentMapper,包名(com.mycompany.mapper)目录结构如下
6.接口StudentMapperr的内容如下
package com.mycompany.mapper; import java.util.List; import com.mycompany.beans.StudentBean; public interface StudentMapper { /** * 新增用户 * @param student * @return * @throws Exception */ public int insertStudent(StudentBean student) throws Exception; /** * 修改用户 * @param student * @param sid * @return * @throws Exception */ public int updateStudent(StudentBean student) throws Exception; /** * 删除用户 * @return * @throws Exception */ public int deleteStudent(int sid) throws Exception; /** * 根据ID查询学生信息 * @return * @throws Exception */ public StudentBean selectStudentById(int sid) throws Exception; /** * 查询所有的学生信息 * @return * @throws Exception */ public List<StudentBean> selectAllStudent() throws Exception; }
7.在src/main/java下创建映射文件StudentMapper.xml,包名(com.mycompany.mapper),目录结构如下
8.映射文件StudentMapper.xml的内容如下
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.mycompany.mapper.StudentMapper"> <!-- 添加学生信息 在各种标签中的id属性必须和接口中的方法名相同 , id属性值必须是唯一的,不能够重复使用。 parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型 --> <insert id="insertStudent" useGeneratedKeys="true" keyProperty="sid"> INSERT INTO student (name) VALUES (#{name}) </insert> <!-- 修改学生信息 --> <update id="updateStudent" parameterType="com.mycompany.beans.StudentBean"> UPDATE student SET name = #{name} WHERE sid = #{sid} </update> <!-- 删除学生信息 --> <delete id="deleteStudent" parameterType="int"> DELETE FROM student WHERE sid=#{sid} </delete> <!-- 根据ID查询学生信息 --> <select id="selectStudentById" parameterType="int" resultMap="studentMap"> SELECT * FROM student WHERE sid=#{sid} </select> <!-- 查询所有学生信息 --> <select id="selectAllStudent" resultMap="studentMap"> SELECT * FROM student </select> <resultMap type="StudentBean" id="studentMap"> <id property="sid" column="sid" javaType="java.lang.Integer"/> <result property="name" column="name" javaType="java.lang.String"/> </resultMap> </mapper>
9.在src/main/java下创建工具类DBUtils,包名(com.mycompany.util)目录结构如下
10.工具类DBUtils的内容如下
package com.mycompany.util; import java.io.IOException; import java.io.Reader; 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 DBUtils { public static SqlSessionFactory sessionFactory; static{ try { Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml"); sessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSession(){ return sessionFactory.openSession(); } }
11.在src/main/resources下创建mysql.properties属性文件,目录结构如下
12.mysql.properties属性文件内容如下
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=
13.在src/main/resources下创建mybatis配置文件mybatis.cfg.xml,目录结构如下
14.配置文件mybatis.cfg.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="mysql.properties"></properties> <typeAliases> <package name="com.mycompany.beans"/> </typeAliases> <!-- 配置mybatis运行环境 --> <environments default="mybatis"> <environment id="mybatis"> <!-- type="JDBC" 代表使用JDBC的提交和回滚来管理事务 --> <transactionManager type="JDBC" /> <!-- mybatis提供了3种数据源类型,分别是:POOLED,UNPOOLED,JNDI --> <!-- POOLED 表示支持JDBC数据源连接池 --> <!-- UNPOOLED 表示不支持数据源连接池 --> <!-- JNDI 表示支持外部数据源连接池 --> <dataSource type="POOLED"> <property name="driver" value="http://www.mamicode.com/${jdbc.driver}" /> <property name="url" value="http://www.mamicode.com/${jdbc.url}" /> <property name="username" value="http://www.mamicode.com/${jdbc.username}" /> <property name="password" value="http://www.mamicode.com/${jdbc.password}" /> </dataSource> </environment> </environments> <mappers> <package name="com/mycompany/mapper"/> </mappers> </configuration>
15.在src/main/java下创建StudentService文件,包名(com.mycompany.service),目录结构如下
16.StudentService文件的内容如下
package com.mycompany.service; import java.util.List; import org.apache.ibatis.session.SqlSession; import com.mycompany.beans.StudentBean; import com.mycompany.mapper.StudentMapper; import com.mycompany.util.DBUtils; public class StudentService { /** * 添加学生信息 * @param student */ public void insertStudent(StudentBean student){ SqlSession session = DBUtils.getSession(); StudentMapper mapper = session.getMapper(StudentMapper.class); try { int result = mapper.insertStudent(student); System.out.println(result); session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); } } /** * 修改学生信息 * @param student */ public void updateStudent(StudentBean student){ SqlSession session = DBUtils.getSession(); StudentMapper mapper = session.getMapper(StudentMapper.class); try { int result = mapper.updateStudent(student); System.out.println(result); session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); } } /** * 删除学生信息 * @param sid */ public void deleteStudent(int sid){ SqlSession session = DBUtils.getSession(); StudentMapper mapper = session.getMapper(StudentMapper.class); try { int result = mapper.deleteStudent(sid); System.out.println(result); session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); } } /** * 根据ID查询学生信息 * @param sid */ public void selectStudentById(int sid){ SqlSession session = DBUtils.getSession(); StudentMapper mapper = session.getMapper(StudentMapper.class); try { StudentBean student = mapper.selectStudentById(sid); System.out.println(student); session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); } } /** * 查询所有学生信息 */ public void selectAllStudent(){ SqlSession session = DBUtils.getSession(); StudentMapper mapper = session.getMapper(StudentMapper.class); try { List<StudentBean> students = mapper.selectAllStudent(); for (StudentBean studentBean : students) { System.out.println(studentBean); } session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); } } }
17.在src/test/java下创建StudentServiceTest测试类,包名(com.mycompany.service)目录结构如下
18.StudentServiceTest测试类的内容如下
package com.mycompany.service; import org.junit.Test; import com.mycompany.beans.StudentBean; public class StudentServiceTest { /** * 测试添加学生信息操作 */ @Test public void insertStudentTest(){ StudentService studentService = new StudentService(); StudentBean student = new StudentBean("test insert"); studentService.insertStudent(student); } /** * 测试修改学生信息操作 */ @Test public void updateStudent(){ StudentService studentService = new StudentService(); StudentBean studentBean = new StudentBean(5,"test update"); studentService.updateStudent(studentBean); } /** * 测试删除学生信息操作 */ @Test public void deleteStudent(){ StudentService studentService = new StudentService(); studentService.deleteStudent(7); } /** * 测试根据ID查询学生信息 */ @Test public void selectStudentById(){ StudentService studentService = new StudentService(); studentService.selectStudentById(8); } /** * 测试查询所有学生信息 */ @Test public void selectAllStudent(){ StudentService studentService = new StudentService(); studentService.selectAllStudent(); } }
本文出自 “素颜” 博客,谢绝转载!
MyBatis-增删改查
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。