尚硅谷-MyBatis的CRUD操作

项目结构:

User实体类代码:

package com.atguigu.mybatis.bean;

public class User {
	private int id;
	private String name;
	private int age;

	public User() {
		super();
	}

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

	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;
	}

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

}

userMapper.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.atguigu.mybatis.bean.userMapper">
	<!--
		CRUD操作
	 -->
	<insert id="addUser" parameterType="User">
		insert into users(name,age) values(#{name},#{age})
	</insert>

	<delete id="deleteUser" parameterType="int">
		delete from users where id=#{id}
	</delete>

	<update id="updateUser" parameterType="User">
		update users set name=#{name},age=#{age} where id=#{id}
	</update>

	<select id="getUser" parameterType="int" resultType="User">
		select * from users where id=#{id}
	</select>

	<select id="getAllUsers" resultType="User">
		select * from users
	</select>
</mapper>

UserMapper注解类代码(要么用xml方式,要么用注解方式):

package com.atguigu.mybatis.test2;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.atguigu.mybatis.bean.User;

public interface UserMapper {

	@Insert("insert into users(name,age) values(#{name},#{age})")
	public int add(User user);

	@Delete("delete from users where id=#{id}")
	public int deleteById(int id);

	@Update("update users set name=#{name},age=#{age} where id=#{id}")
	public int update(User user);

	@Select("select * from users where id=#{id}")
	public User getById(int id);

	@Select("select * from users")
	public List<User> getAll();
}

获取SqlSessionFactory工厂的MybatisUtils代码:

package com.atguigu.mybatis.utils;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtils {

	public static SqlSessionFactory getFactory() {
		String resource = "conf.xml";
		InputStream inputStream = MybatisUtils.class.getClassLoader().getResourceAsStream(resource);

		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);

		return factory;
	}
}

配置文件conf.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="db.properties"/>
	<!-- 为实体类定义别名,简化sql映射xml文件中的引用-->
	<typeAliases>
		<!-- <typeAlias type="com.atguigu.mybatis.bean.User" alias="User"/> -->
		<!-- 该包下的所有类以其简单类名为实体类别名(如:User类的别名为User) -->
		<package name="com.atguigu.mybatis.bean"/>
	</typeAliases>
	<!--
		development : 开发模式
		work : 工作模式
 	-->
	<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="${name}" />
				<property name="password" value="${password}" />
			</dataSource>
		</environment>
	</environments>

	<mappers>
		<mapper resource="com/atguigu/mybatis/bean/userMapper.xml"/>
		<mapper class="com.atguigu.mybatis.test2.UserMapper"/>
	</mappers>
</configuration>

测试类Test2代码:

package com.atguigu.mybatis.test2;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;

import com.atguigu.mybatis.bean.User;
import com.atguigu.mybatis.utils.MybatisUtils;

/*
 * 测试: CRUD操作的XML的实现和注解实现
 */
public class Test2 {
	//--------------------------------测试XML的实现
	@Test
	public void testAdd(){
		SqlSessionFactory factory=MybatisUtils.getFactory();
		//默认是手动提交的
		SqlSession session=factory.openSession();

		String statement="com.atguigu.mybatis.bean.userMapper.addUser";
		int insert=session.insert(statement, new User(-1, "KK", 23));
		//提交事务
		session.commit();

		session.close();
		System.out.println(insert);
	}

	@Test
	public void testUpdate(){
		SqlSessionFactory factory=MybatisUtils.getFactory();
		//默认是手动提交
		SqlSession session=factory.openSession(true);
		String statement = "com.atguigu.mybatis.bean.userMapper.updateUser";
		int update =session.update(statement,new User(3, "KKK111", 25));
		session.close();
		System.out.println(update);
	}

	@Test
	public void testDelete(){
		SqlSessionFactory factory=MybatisUtils.getFactory();
		//默认是手动提交
		SqlSession session=factory.openSession(true);
		String statement = "com.atguigu.mybatis.bean.userMapper.deleteUser";
		int delete =session.delete(statement,3);
		session.close();
		System.out.println(delete);
	}

	@Test
	public void testGetUser(){
		SqlSessionFactory factory=MybatisUtils.getFactory();
		//默认是手动提交
		SqlSession session=factory.openSession(true);
		String statement = "com.atguigu.mybatis.bean.userMapper.getUser";
		User user=session.selectOne(statement, 1);
		session.close();
		System.out.println(user);
	}

	@Test
	public void testGetAll(){
		SqlSessionFactory factory=MybatisUtils.getFactory();
		//默认是手动提交
		SqlSession session=factory.openSession(true);
		String statement = "com.atguigu.mybatis.bean.userMapper.getAllUsers";
		List<User> list=session.selectList(statement);
		session.close();
		System.out.println(list);
	}

	//--------------------------------测试注解的实现
	@Test
	public void testAdd2(){
		SqlSessionFactory factory=MybatisUtils.getFactory();
		SqlSession session=factory.openSession(true);

		UserMapper mapper=session.getMapper(UserMapper.class);
		int add=mapper.add(new User(-1, "SS", 34));
		session.close();
		System.out.println(add);
	}
}

数据库配置代码db.properties:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis
name=root
password=123456

可以在src下加入log4j的配置文件,打印日志信息:

-->首先添加   log4j-1.2.16.jar

-->然后:

log4j.properties(方式一)

        log4j.properties,
	log4j.rootLogger=DEBUG, Console
	#Console
	log4j.appender.Console=org.apache.log4j.ConsoleAppender
	log4j.appender.Console.layout=org.apache.log4j.PatternLayout
	log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
	log4j.logger.java.sql.ResultSet=INFO
	log4j.logger.org.apache=INFO
	log4j.logger.java.sql.Connection=DEBUG
	log4j.logger.java.sql.Statement=DEBUG
	log4j.logger.java.sql.PreparedStatement=DEBUG

log4j.xml(方式二)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
	<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern"
				value="%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) \n" />
		</layout>
	</appender>
	<logger name="java.sql">
		<level value="debug" />
	</logger>
	<logger name="org.apache.ibatis">
		<level value="debug" />
	</logger>
	<root>
		<level value="debug" />
		<appender-ref ref="STDOUT" />
	</root>
</log4j:configuration>
时间: 2024-10-15 09:28:46

尚硅谷-MyBatis的CRUD操作的相关文章

【MyBatis】MyBatis实现CRUD操作

1.实现基本CRUD功能 使用MyBatis对数据完整的操作,也就是CRUD功能的实现.根据之前的内容,要想实现CRUD,只需要进行映射文件的配置. 范例:修改EmpMapper.xml文件,实现CRUD <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http:/

尚硅谷-mybatis快速入门

1. Mybatis介绍(ibatis) MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录. JDBC--->dbutils(自动封装)--->MyBatis--->Hibernate 2. mybatis快速入

Spring boot 入门三:spring boot 整合mybatis 实现CRUD操作

开发环境延续上一节的开发环境这里不再做介绍 添加mybatis依赖 <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> DAO层接口(这里是直接通过注解实现数据库操作,不

基于MyBatis的CRUD操作

一.基于XML实现1.定义SQL映射XML文件studentMapper.xml:<mapper namespace="com.mapping.studentMapper">    <!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getStudent,id属性值必须是唯一的,不能够重复    使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型    resultType=&

mybatis实现CRUD操作和优化代码及调试(mysql数据库)(三)

继续(二)说 1.工程结构 2.新建db.properties文件(我的数据库没有设置密码) driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis name=root password= 3.log4j.jar加入工程并添加log4j.xml文件 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:conf

java之mybatis之使用mybatis实现crud操作

目录结构: 1.封装 mybatis 的工具类: MybatisUtil.java public class MybatisUtil { private static SqlSessionFactory getSqlSessionFactory() throws IOException{ Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml"); return new SqlSessionFactoryBuilde

2018年尚硅谷《全套Java、Android、HTML5前端视频》

全套整合一个盘里:链接:https://pan.baidu.com/s/1nwnrWOp 密码:h4bw 如果分类里没有请下载下边那些小项教程链接 感谢尚硅谷提供的视频教程:http://www.atguigu.com/ [全套Java教程--打包下载地址]Java基础阶段一.20天横扫Java基础(课堂实录)https://pan.baidu.com/s/1jJpzHv4 二.尚硅谷Java基础实战--Bank项目http://pan.baidu.com/share/link?shareid=

使用MyBatis对表执行CRUD操作

一.使用MyBatis对表执行CRUD操作——基于XML的实现 1.定义sql映射xml文件 userMapper.xml文件的内容如下: 1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-ma

Mybatis学习(二) - CRUD操作(增删改查操作)

直接上例子: 1.项目结构: 2.具体代码及配置 User.java package com.mybatis.bean; public class User { private int id; private String name; private int age; public User(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } public User(){} publi