MyBatis基础-03-MyBatis增删改查操作

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.monkey1024</groupId>
  <artifactId>01mybatis</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
	  	<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		    <version>3.4.6</version>
		</dependency>
		<dependency>
		    <groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		    <version>5.1.46</version>
		</dependency>
		<dependency>
		    <groupId>log4j</groupId>
		    <artifactId>log4j</artifactId>
		    <version>1.2.17</version>
		</dependency>
		<dependency>
		  <groupId>commons-io</groupId>
		  <artifactId>commons-io</artifactId>
		  <version>2.6</version>
		</dependency>
		<dependency>
		  <groupId>commons-fileupload</groupId>
		  <artifactId>commons-fileupload</artifactId>
		  <version>1.3.3</version>
		</dependency>
		<dependency>
		   <groupId>org.hibernate</groupId>
		   <artifactId>hibernate-validator</artifactId>
		   <version>6.0.9.Final</version>
		</dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.4.RELEASE</version>
        </dependency>

    </dependencies>
    <build>
    	<!-- 与工程名一致 -->
        <finalName>01mybatis</finalName>
        <resources>
        	<resource>
        		<directory>src/main/java</directory>
        		<includes>
        			<include>**/*.xml</include>
        		</includes>
        	</resource>
        </resources>
        <plugins>
            <!-- 编译插件,指定编译用的的jdk版本 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <!-- jdk的版本号 -->
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

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>

	<!-- 注册db配置文件 -->
	<properties resource="db.properties"/>
	
	<!-- mybatis配置文件中的标签是有顺序的 -->
	<!-- 注册实体类的权限定义名的别名 -->
	<typeAliases>
		<!-- 方式一:这种方式配置不太方便 -->
		<typeAlias type="com.monkey1024.bean.Student" alias="student"/>
		<!-- 方式二:mybatis会在这个包下搜索需要的javabean -->
		<package name="com.monkey1024.bean"/>
	</typeAliases>
	
	
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.user}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--注册映射文件-->
        <mapper resource="com/monkey1024/dao/StudentMapper.xml"/>
    </mappers>
</configuration>

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="monkey1024">
	<!-- parameterType可省略 -->
	<insert id="insertStudent" parameterType="student">
		INSERT INTO t_student(name,age,score) VALUES (#{name},#{age},#{score})
		<!-- 获取自增的主键 -->
		<selectKey resultType="int" keyProperty="id" order="AFTER">
			select @@identity
		</selectKey>
	</insert>
	
	
	<!-- 这里的#{xxx}只是起着占位符的作用 -->
	<delete id="deleteStudent">
		delete from t_student where id=#{id}
	</delete>
	
	<update id="updateStudent">
		update t_student set name=#{name},age=#{age},score=#{score} where id=#{id}
	</update>
	
	<!-- resultType要写上单条数据对应的类 -->
	<!-- 查询中尽量不要出现*会影响sql的执行效率 -->
	<select id="selectAllStudent" resultType="student">
		select id,name,age,score from t_student
	</select>
	
	<select id="selectStudentById" resultType="student">
		select id,name,age,score from t_student where id=#{id}
	</select>
	
	<select id="selectStudentByName" resultType="student">
		<!-- select id,name,age,score from t_student where name like '%' #{name} '%' -->
		<!-- 有sql注入问题 -->
		select id,name,age,score from t_student where name like '%${value}%'
	</select>
</mapper>

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/learnmybatis?useSSL=false
jdbc.user=root
jdbc.password=666666

log4j.properties

#log4j.rootLogger=debug,console
log4j.logger.monkey1024=debug,concole
#\u63A7\u5236\u53F0\u9644\u52A0\u5668
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern = [%-5p][%d{yyyy-MM--dd HH:mm:ss}]%m%n

Student.java

package com.monkey1024.bean;


//手动的设置别名
//@Alias("stu")
public class Student {
	private int id;
	private String name;
	private int age;
	private double score;
	
	
	
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + ", score=" + score + "]";
	}

	public Student(String name, int age, double score) {
		this.name = name;
		this.age = age;
		this.score = score;
	}
	public Student(int id, String name, int age, double score) {
		this.id = id;
		this.name = name;
		this.age = age;
		this.score = score;
	}
	
	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;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getId(){
		return id;
	}
	public void setId(int id){
		this.id = id;
	}
	public String getName(){
		return name;
	}
}

StudentDao.java

package com.monkey1024.dao;

import java.util.List;

import com.monkey1024.bean.Student;

public interface StudentDao {
	void  insertStudent(Student student);
	
	void deleteStudent(int id);
	
	void updateStudent(Student student);
	
	List<Student> selectAllStudent();
	
	Student selectStudentById(int id);
	
	List<Student> selectStudentByName(String name);
}

StudentDaoImpl.java

package com.monkey1024.dao.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.monkey1024.bean.Student;
import com.monkey1024.dao.StudentDao;
import com.monkey1024.util.MyBatisUtil;

public class StudentDaoImpl implements StudentDao {

	@Override
	public void insertStudent(Student student) {
		// sqlSession实现了AutoCloseable接口,所以可以自动关闭
		try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
			// 新增操作
			sqlSession.insert("insertStudent", student);

			// 主键的生成跟事务是否提交没有关系,只要执行了sql语句,那就会分配一个主键
			System.out.println("提交事务之前: " + student);
			// 提交事务
			sqlSession.commit();
			// 回滚
			// sqlSession.rollback();
		}
	}

	public void deleteStudent(int id) {
		try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
			// 删除
			sqlSession.delete("deleteStudent", id);
			// 提交
			sqlSession.commit();
		}
	}

	public void updateStudent(Student student) {
		try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
			// 修改
			sqlSession.update("updateStudent", student);
			sqlSession.commit();
		}
	}

	public List<Student> selectAllStudent() {
		List<Student> result = null;
		try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
			// 查询
			result = sqlSession.selectList("selectAllStudent");
		}
		return result; 
	}
	
	public Student selectStudentById(int id){
		Student student = null;
		try(SqlSession sqlSession = MyBatisUtil.getSqlSession()){
			//根据id查询数据
			student = sqlSession.selectOne("selectStudentById",id);
		}
		return student;
	}
	
	public List<Student> selectStudentByName(String name){
		List<Student> result = null;
		try(SqlSession sqlSession = MyBatisUtil.getSqlSession()){
			//查询
			result = sqlSession.selectList("selectStudentByName",name);
		}
		return result;
	}
}

MyBatisUtil.java

package com.monkey1024.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/*
 * DCL的单例模式
 */
public class MyBatisUtil {
	// 无需将构造方法私有化,因为这里面只要保证创建一个SqlSessionFactory的对象
	// private MyBatisUtil()
	private static volatile SqlSessionFactory sqlSessionFactory;

	public static SqlSession getSqlSession() {
		try {
			if (sqlSessionFactory == null) {
				// 读取主配置文件
				InputStream input = Resources.getResourceAsStream("mybatis.xml");
				synchronized (MyBatisUtil.class) {
					if (sqlSessionFactory == null) {
						sqlSessionFactory = new SqlSessionFactoryBuilder().build(input);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		//mybatis自动提交事务
//		return sqlSessionFactory.openSession(true);
		return sqlSessionFactory.openSession();

	}
}

StudentTest01.java

package com.monkey1024.test;

import java.util.List;

import org.junit.Before;
import org.junit.Test;

import com.monkey1024.bean.Student;
import com.monkey1024.dao.StudentDao;
import com.monkey1024.dao.impl.StudentDaoImpl;

public class StudentTest01 {
	
	
	private StudentDao studentDao;
	
	@Before
	public void initStudentDao(){
		studentDao = new StudentDaoImpl();
	}
	@Test
	public void insertStudent(){
		Student student = new Student("jyd",52,98.5);
		
		//id的默认值是0
		System.out.println(student);
		studentDao.insertStudent(student);
		//可以获取到id的值
		System.out.println(student);
	}
	
	@Test
	public void deleteStudent(){
		//删除id是2的数据
		studentDao.deleteStudent(2);
	}
	@Test
	public void updateStudent(){
		Student student = new Student("周杰伦",40,99);
		student.setId(4);
		studentDao.updateStudent(student);
	}
	@Test
	public void selectAllStudent(){
		List<Student> students = studentDao.selectAllStudent();
//		System.out.println(students);
		//jdk8新增的foreach方法+lambda表达式
		students.forEach((s->{
			System.out.println(s);
		}));
	}
	@Test
	public void selectStudentById(){
		Student student = studentDao.selectStudentById(7);
		System.out.println(student);
	}
	@Test
	public void selectStudentByName(){
		List<Student> students = studentDao.selectStudentByName("j");
		//jdk8新增的foreach方法+lambda表达式
		students.forEach((s->{
			System.out.println(s);
		}));
		
	}
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值