文档章节

mybatis 简单的CRUD

小代码2016
 小代码2016
发布于 2016/03/13 15:25
字数 902
阅读 71
收藏 1

目录列表:


D:\code\smvc\mybatis-one>tree src /f
卷 软件 的文件夹 PATH 列表
卷序列号为 0000-CD08
D:\CODE\SMVC\MYBATIS-ONE\SRC
├─main
│  └─java
│      │  jdbc.properties
│      │  mybatis-config.xml
│      │
│      └─com
│          └─laolang
│              ├─domain
│              │      Student.java
│              │      StudentMapper.xml
│              │
│              ├─mapper
│              │      StudentMapper.java
│              │
│              ├─services
│              │      StudentService.java
│              │
│              └─util
│                      MybatisUtil.java
│
└─test
    └─java
        └─com
            └─laolang
                └─service
                        StudentServiceTest.java


D:\code\smvc\mybatis-one>


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.laolang.mybatis-study</groupId>
	<artifactId>mybatis-one</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>mybatis-one</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.6</version>
		</dependency>

		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.2</version>
		</dependency>

	</dependencies>
</project>


mybatis配置


jdbc.properties


driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis_study
username=root
password=root


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>

	<!-- 加载 jdbc properties 文件 -->
	<properties resource="jdbc.properties" />

	<typeAliases>
		<typeAlias alias="Student" type="com.laolang.domain.Student" />
	</typeAliases>
	
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${driver}" />
				<property name="url" value="${url}" />
				<property name="username" value="${username}" />
				<property name="password" value="${password}" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="com/laolang/domain/StudentMapper.xml" />
	</mappers>
</configuration>


实体类及CRUD操作实现


com.laolang.domain.Student


package com.laolang.domain;

public class Student {

	public Student() {
		super();
	}

	public Student(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	public Student(int id, String name, int age, String sex) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age
				+ ", sex=" + sex + "]";
	}

	public int getId() {
		return id;
	}

	public void setId(int 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 String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	private int id;
	private String name;
	private int age;
	private String sex;
}


com.laolang.domain.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="com.laolang.mapper.StudentMapper">
	<resultMap type="Student" id="StudentResult">
		<id property="id" column="id"/>
		<result property="name" column="name"/>
		<result property="age" column="age"/>
		<result property="sex" column="sex"/>
	</resultMap>
	
	<select id="selectAll" resultMap="StudentResult">
		select id,name,age,sex from student
	</select>
	
	<select id="selectById" parameterType="int" resultType="Student">
		select id,name,age,sex from student where id = #{id} 
	</select>
	
	<select id="selectByName" parameterType="String" resultType="Student">
		select id,name,age,sex from student where name = #{name}
	</select>
	
	<insert id="insertStudent" parameterType="Student" useGeneratedKeys="true" keyProperty="id">
		insert into student ( name, age, sex ) values(#{name},#{age},#{sex})
	</insert>
	
	<update id="updateStudent" parameterType="Student">
		update student set name = #{name} , age = #{age} , sex = #{age}
		where id = #{id}
	</update>
	
	<delete id="deleteStudentById" parameterType="int">
		delete from student where id = #{id}
	</delete>
	
</mapper>


com.laolang.mapper.StudentMapper



package com.laolang.mapper;

import java.util.List;

import com.laolang.domain.Student;

public interface StudentMapper {

	public List<Student> selectAll();

	public Student selectById(int id);

	public Student selectByName(String name);
	
	public void insertStudent(Student student );
	
	public void updateStudent(Student student );
	
	public void deleteStudentById(int id );
}


com.laolang.services.StudentServices



package com.laolang.services;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.laolang.domain.Student;
import com.laolang.mapper.StudentMapper;
import com.laolang.util.MybatisUtil;

public class StudentService {

	public List<Student> selectAll() {
		SqlSession session = MybatisUtil.openSession();

		try {
			StudentMapper studentMapper = session
					.getMapper(StudentMapper.class);
			return studentMapper.selectAll();
		} finally {
			session.close();
		}
	}

	public Student selectById(int id) {
		SqlSession session = MybatisUtil.openSession();

		try {
			StudentMapper studentMapper = session
					.getMapper(StudentMapper.class);
			return studentMapper.selectById(id);
		} finally {
			session.close();
		}
	}

	public Student selectByName(String name) {
		SqlSession session = MybatisUtil.openSession();

		try {
			StudentMapper studentMapper = session
					.getMapper(StudentMapper.class);
			return studentMapper.selectByName(name);
		} finally {
			session.close();
		}
	}

	public void insertStudent(Student stu) {
		SqlSession session = MybatisUtil.openSession();

		try {
			StudentMapper studentMapper = session
					.getMapper(StudentMapper.class);
			studentMapper.insertStudent(stu);
			session.commit();
		} finally {
			session.close();
		}
	}

	public void updateStudent(Student student) {
		SqlSession session = MybatisUtil.openSession();

		try {
			StudentMapper studentMapper = session
					.getMapper(StudentMapper.class);
			studentMapper.updateStudent(student);
			session.commit();
		} finally {
			session.close();
		}
	}

	public void deleteStudentById(int id) {
		SqlSession session = MybatisUtil.openSession();

		try {
			StudentMapper studentMapper = session
					.getMapper(StudentMapper.class);
			studentMapper.deleteStudentById(id);
			session.commit();
		} finally {
			session.close();
		}
	}

}


测试文件 :


StudentServiceTest


package com.laolang.service;

import java.util.List;

import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

import com.laolang.domain.Student;
import com.laolang.services.StudentService;

public class StudentServiceTest {

	@BeforeClass
	public static void setUp() {
		studentService = new StudentService();
	}

	@Ignore
	@Test
	public void testSelectAll() {
		System.out.println("-->查询所有-----------");
		List<Student> students = studentService.selectAll();
		for (Student stu : students) {
			System.out.println(stu);
		}
		System.out.println("---------------------------\n\n");
	}

	@Ignore
	@Test
	public void testSelectById() {
		System.out.println("-->通过 id 查询-----------");
		Student stu = studentService.selectById(1);
		System.out.println(stu);
		System.out.println("---------------------------\n\n");
	}

	@Ignore
	@Test
	public void testSelectByName() {
		System.out.println("-->通过 name 查询-----------");
		Student stu = studentService.selectByName("小代码");
		System.out.println(stu);
		System.out.println("---------------------------\n\n");
	}

	@Ignore
	@Test
	public void testInsertStudent() {
		System.out.println("-->插入-----------");
		String name = "天涯";
		Student stu = new Student(name, 34, "男");
		studentService.insertStudent(stu);
		stu = studentService.selectByName(name);
		System.out.println(stu);
		System.out.println("---------------------------\n\n");
	}

	@Ignore
	@Test
	public void testUpdateStudent() {
		System.out.println("-->修改-----------");
		Student stu = studentService.selectById(1);
		System.out.println();
		stu.setName("xiaodaima");
		studentService.updateStudent(stu);
		stu = studentService.selectById(1);
		System.out.println(stu);
		System.out.println("---------------------------\n\n");
	}

	@Ignore
	@Test
	public void testDeleteStudentById() {
		System.out.println("-->删除-----------");
		List<Student> studentList = studentService.selectAll();
		for( Student stu : studentList ){
			System.out.println(stu);
		}
		studentService.deleteStudentById(7);
		System.out.println("删除后:\n");
		studentList = studentService.selectAll();
		for( Student stu : studentList ){
			System.out.println(stu);
		}
		System.out.println("---------------------------\n\n");
		
	}

	private static StudentService studentService;
}



需要测试哪个方法,则把@Ignore去掉即可


© 著作权归作者所有

共有 人打赏支持
小代码2016
粉丝 36
博文 328
码字总数 153495
作品 0
安阳
程序员
mybatis 通用CRUD的替换方法

http://git.oschina.net/alexgaoyh/MutiModule-parent 代码此次变更较大,使用了mybatis-generator-maven-plugin 插件,把之前多模块项目中的domain部分删除,将这一部分代码整合到persise部...

alexgaoyh
2015/04/22
0
1
构建dubbo分布式平台-maven构建ant-framework核心代码Base封装

因为涉及到springmvc、mybatis的集成,为了使项目编码更简洁易用,这边将基础的BASE进行封装,其中包括:BaseBean、BaseDao、BaseService、CRUD的基础封装、分页组件的封装、mybatis的mappe...

明理萝
08/28
0
0
baomidou/mybatisplus-spring-boot-starter

#mybatisplus-spring-boot-starter mybatisplus-spring-boot-starter 为 Mybatis-Plus 快速集成 spring-boot 简化配置而生,不再需拿 MyBatis 和 Hibernate 相比,mybatis-plus 作为 mybati......

baomidou
2017/05/05
0
0
baomidou/mybatis-plus

为简化开发工作、提高生产率而生 简介 | Intro Mybatis 增强工具包 - 只做增强不做改变,简化操作 技术讨论 QQ 群 576493122 优点 | Advantages 无侵入:Mybatis-Plus 在 Mybatis 的基础上进...

baomidou
2016/01/25
0
0
mybatis-plus的使用 ------ 入门

前言: mybatis在持久层框架中还是比较火的,一般项目都是基于ssm。虽然mybatis可以直接在xml中通过SQL语句操作数据库,很是灵活。但正其操作都要通过SQL语句进行,就必须写大量的xml文件,很...

贪挽懒月
08/24
0
0

没有更多内容

加载失败,请刷新页面

加载更多

70.shell的函数 数组 告警系统需求分析

20.16/20.17 shell中的函数 20.18 shell中的数组 20.19 告警系统需求分析 20.16/20.17 shell中的函数: ~1. 函数就是把一段代码整理到了一个小单元中,并给这个小单元起一个名字,当用到这段...

王鑫linux
28分钟前
0
0
分布式框架spring-session实现session一致性使用问题

前言:项目中使用到spring-session来缓存用户信息,保证服务之间session一致性,但是获取session信息为什么不能再服务层获取? 一、spring-session实现session一致性方式 用户每一次请求都会...

WALK_MAN
50分钟前
3
0
C++ yield()与sleep_for()

C++11 标准库提供了yield()和sleep_for()两个方法。 (1)std::this_thread::yield(): 线程调用该方法时,主动让出CPU,并且不参与CPU的本次调度,从而让其他线程有机会运行。在后续的调度周...

yepanl
58分钟前
1
0
Java并发编程实战(chapter_3)(线程池ThreadPoolExecutor源码分析)

这个系列一直没再写,很多原因,中间经历了换工作,熟悉项目,熟悉新团队等等一系列的事情。并发课题对于Java来说是一个又重要又难的一大块,除非气定神闲、精力满满,否则我本身是不敢随便写...

心中的理想乡
今天
22
0
shell学习之获取用户的输入命令read

在运行脚本的时候,命令行参数是可以传入参数,还有就是在脚本运行过程中需要用户输入参数,比如你想要在脚本运行时问个问题,并等待运行脚本的人来回答。bash shell为此提 供了read命令。 ...

woshixin
今天
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部