文档章节

mybatis 简单的CRUD

小代码2016
 小代码2016
发布于 2016/03/13 15:25
字数 902
阅读 72
收藏 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去掉即可


© 著作权归作者所有

共有 人打赏支持
下一篇: Hibernate CRUD
小代码2016
粉丝 37
博文 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
XiaoBingBy/bing-upms

简介 Bing-UPMS是一个轻量级的Spring Boot快速开发平台,学习简单、轻量级、易扩展;使用最新技术。 DEMO Bing-UPMS DEMO-----------企业站点 Demo Bing-UPMS + 在线学习系统 点击观看 OSS ...

XiaoBingBy
2017/11/05
0
0

没有更多内容

加载失败,请刷新页面

加载更多

OSChina 周日乱弹 —— 钱不还,我就当你人不在了

Osc乱弹歌单(2018)请戳(这里) 【今日歌曲】 @莱布妮子 :分享Bigleaf的单曲《小鹿》 《小鹿》- Bigleaf 手机党少年们想听歌,请使劲儿戳(这里) 周日在家做什么? 做手工呀, @poorfis...

小小编辑
28分钟前
11
1
EOS docker开发环境

使用eos docker镜像是部署本地EOS开发环境的最轻松愉快的方法。使用官方提供的eos docker镜像,你可以快速建立一个eos开发环境,可以迅速启动开发节点和钱包服务器、创建账户、编写智能合约....

汇智网教程
今天
17
0
《唐史原来超有趣》的读后感优秀范文3700字

《唐史原来超有趣》的读后感优秀范文3700字: 作者:花若离。我今天分享的内容《唐史原来超有趣》这本书的读后感,我将这本书看了一遍之后就束之高阁了,不过里面的内容一直在在脑海中回放,...

原创小博客
今天
20
0
IC-CAD Methodology知识图谱

CAD (Computer Aided Design),计算机辅助设计,指利用计算机及其图形设备帮助设计人员进行设计工作,这个定义同样可以用来近似描述IC公司CAD工程师这个岗位的工作。 早期IC公司的CAD岗位最初...

李艳青1987
今天
24
0
CompletableFuture get方法一直阻塞或抛出TimeoutException

问题描述 最近刚刚上线的服务突然抛出大量的TimeoutException,查询后发现是使用了CompletableFuture,并且在执行future.get(5, TimeUnit.SECONDS);时抛出了TimeoutException异常,导致接口响...

xiaolyuh
今天
11
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部