欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mybatis 一:基本的配置框架

程序员文章站 2022-03-30 10:16:04
mybatis配置需要的jar包: <!-- MySQL的jar包 --><dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1...

mybatis配置

需要的jar包:

    <!-- MySQL的jar包 -->
	<dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>5.1.47</version>
	</dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
	<dependency>
	    <groupId>org.mybatis</groupId>
	    <artifactId>mybatis</artifactId>
	    <version>3.4.6</version>
	</dependency>

 为配置文件的文件夹下加入mybatis-3-config.dtd和mybatis-3-mapper.dtd

mybatis 一:基本的配置框架

dtd是xml文件的约束语言,包括mybatis-3-config.dtd,mybatis-3-mapper.dtd

设置eclipse对于xml文件编写的快捷键:在window下打开Preferences搜索xml

mybatis 一:基本的配置框架

点击添加,然后location选择mybatis-3-config.dtd,mybatis-3-mapper.dtd所放置的位置,Key type选择URI。config.xml和mapper.xml的key分别为:http://mybatis.org/dtd/mybatis-3-config.dtdhttp://mybatis.org/dtd/mybatis-3-mapper.dtd

 mybatis 一:基本的配置框架

添加好就可以在书写xml的时候使用快捷键了。 

框架的搭建:

书写配置文件database.properties:其为一个键值对形式的文本文件

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

1.将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>
	<properties resource="database.properties"></properties>
	<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="mapper/UserMapper.xml"></mapper>
	</mappers>
</configuration>

2.在Java里书写bean包:bean包的名字要与数据库的名字一致,否则会映射不了或则需要手动映射。

package bean;
public class UserInfo {
	private Integer userId;
	private String userName;
	private String userSex;
	private Integer userAge;
	private String userAddress;
	private Integer userState;
	……构造器,get,set,toString……
}
package bean;
public class Entity1 {
	private Integer startAge;
	private Integer endAge;
	……构造器,get,set,toString……
}
package bean;
// 分页Bean
public class PageInfo {
	private Integer page; // 当前页数
	private Integer number;// 每页显示多少条
	private Integer allNumber; // 总条数
	private Integer allPage;// 总页数
	private Integer startNumber;
    ……构造器,get,set,toString……
}

 3.书写Java的mapper接口(在这里声明了对数据库的操作):

package mapper;

import java.util.List;
import java.util.Map;

import bean.Entity1;
import bean.PageInfo;
import bean.UserInfo;

public interface UserMapper { //UserInfoDAO
	List<UserInfo> findAllUser();//查询所有的用户
	List<UserInfo> findUserBySex(String a33);//按照性别查询
	List<UserInfo> find1();
	List<UserInfo> find2(Map<String, Integer> map);//使用一个map封装多个参数
	List<UserInfo> find3(Entity1 e);
        //添加操作
	void addUser(UserInfo ui);
	void deleteUser(int id);
	void updateUser(UserInfo ui);
	List<UserInfo> findPage(PageInfo pi);
	Integer findAllUserCount();//查询总人数,用于分页查询
}

4.创建mapper接口所对应的mapper.xml:

  1. id:对应mapper接口中的方法名,这里名称必须唯一。
  2. resultType:返回值类型,如果是集合,这里指定泛型。
  3. parameterType:参数     在语句中使用方式为  #{形参名}
    1. 特点:传参时只能传一个参数(多个参数可以封装起来,即多个值)

      1. 使用一个<String,int>的map进行封装,
      2. 使用一个封装类进行封装。
<?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="mapper.UserMapper">
	<!-- 手动进行映射 -->
	<resultMap type="bean.UserInfo" id="abc">
		<!-- 映射主键 -->
		<id column="id" property="userId" />
		<!-- 映射普通键 -->
		<result column="age" property="userAge" />
		<result column="sex" property="userSex" />
		<result column="address" property="userAddress" />
		<!-- 映射关系 -->
	</resultMap>
	<!-- id:对应的方法名,这里的名字必须唯一 resultType:返回类型,如果是集合,这里指定泛型 -->
	<select id="findAllUser" resultType="bean.UserInfo">
		select * from UserInfo
	</select>
	<select id="findUserBySex" resultType="bean.UserInfo"
		parameterType="String">
		select * from userinfo where usersex=#{a33}
	</select>
	<select id="find1" resultMap="abc">
		SELECT userid AS id
		,username,usersex AS sex,userage AS age,useraddress AS address FROM
		userinfo
	</select>

	<select id="find2" resultType="bean.UserInfo">
		select * from userinfo where
		userage between #{startAge} and #{endAge}
	</select>
	<select id="find3" resultType="bean.UserInfo"
		parameterType="bean.Entity1">
		select * from userinfo where
		userage between #{startAge}
		and #{endAge}
	</select>

	<!-- 添加操作 -->
	<insert id="addUser" parameterType="bean.UserInfo" >
		insert into userinfo values(null,#{userName},#{userSex},${userAge},#{userAddress},md5('123456'),1)
	</insert>

	<delete id="deleteUser">
		delete from userinfo where userid=#{id}
	</delete>

	<insert id="updateUser" parameterType="bean.UserInfo">
		update userinfo set username=#{userName} where userid=#{userId}
	</insert>

	<!-- 分页开始 -->
	<select id="findPage" parameterType="bean.PageInfo" resultType="bean.UserInfo">
		select * from UserInfo LIMIT #{startNumber},#{number}
	</select>
	
	<select id="findAllUserCount" resultType="java.lang.Integer">
		select count(userId) from UserInfo
	</select>


</mapper>

注意:包中的属性名对应的是虚表的列名,当sql语句中没有重命名时,虚表与实表的列名相同。

手动映射:(当sql语句中出现了重命名时,使用)

<mapper namespace="mapper.StuMapper">
	<!-- 手动映射 -->
	<resultMap type="bean.Tongxingongcheng" id="123">
		<!-- 映射主键 -->
		<id column="id" property="stuid"/>
		<!-- 映射普通键 -->
		<result column="class" property="stuclass"/>
	</resultMap>

5.书写biz包,并在biz包中实现分页查询:

package biz;

import java.io.InputStream;
import java.util.List;

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

import bean.PageInfo;
import bean.UserInfo;
import mapper.UserMapper;
import test.Test;

public class UserBiz {

	private UserMapper um;

	public UserBiz() {//构造器
		// 加载配置文件信息
		InputStream in = Test.class.getClassLoader().getResourceAsStream("config.xml");
		// 创建会话工厂
		SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
		// 创建会话:CRUD 这里已经自动开启事务
		SqlSession session = ssf.openSession();
		// 通过代理,MyBatis产生UserMapper的实现类 执行相关操作
		um = session.getMapper(UserMapper.class);
	}

	public List<UserInfo> findPage(PageInfo pi) {
		pi.setStartNumber((pi.getPage()-1)*pi.getNumber());
		return um.findPage(pi);
	}

	// 当前第M/N页 每页显示X条  总条数X  
	public void showMsg(PageInfo pi) {
		pi.setAllNumber(um.findAllUserCount());
		pi.setAllPage(pi.getAllNumber()%pi.getNumber()==0?(pi.getAllNumber()/pi.getNumber()):(pi.getAllNumber()/pi.getNumber()+1));
		String str = "当前第"+pi.getPage()+"/"+pi.getAllPage()+"页 每页显示"+pi.getNumber()+"条  总条数"+pi.getAllNumber();
		
		System.out.println(str);
	}
	
}

6.书写test类:

package test;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.Transaction;

import bean.Entity1;
import bean.PageInfo;
import bean.UserInfo;
import biz.UserBiz;
import mapper.UserMapper;

// ibatis 1 2 3  mybaits 3
public class Test {

	public void a() {
		// 加载配置文件信息
		InputStream in = Test.class.getClassLoader().getResourceAsStream("config.xml");
		// 创建会话工厂
		SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
		// 创建会话:CRUD 这里已经自动开启事务
		SqlSession session = ssf.openSession();
		// 通过代理,MyBatis产生UserMapper的实现类 执行相关操作
		UserMapper um = session.getMapper(UserMapper.class);
		List<UserInfo> list = um.find1();
		for (UserInfo ui : list) {
			System.out.println(ui);
		}
		// 提交或者回滚事务
		session.commit();
		// 关闭会话
		session.close();
	}

	public void b() {
		// 加载配置文件信息
		InputStream in = Test.class.getClassLoader().getResourceAsStream("config.xml");
		// 创建会话工厂
		SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
		// 创建会话:CRUD 这里已经自动开启事务
		SqlSession session = ssf.openSession();
		// 通过代理,MyBatis产生UserMapper的实现类 执行相关操作
		UserMapper um = session.getMapper(UserMapper.class);

		Map<String, Integer> map = new HashMap<>();
		map.put("startAge", 35);
		map.put("endAge", 42);

		List<UserInfo> list = um.find2(map);
		for (UserInfo ui : list) {
			System.out.println(ui);
		}
		// 提交或者回滚事务
		session.commit();
		// 关闭会话
		session.close();
	}

	public void c() {
		// 加载配置文件信息
		InputStream in = Test.class.getClassLoader().getResourceAsStream("config.xml");
		// 创建会话工厂
		SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
		// 创建会话:CRUD 这里已经自动开启事务
		SqlSession session = ssf.openSession();
		// 通过代理,MyBatis产生UserMapper的实现类 执行相关操作
		UserMapper um = session.getMapper(UserMapper.class);

		Entity1 e = new Entity1();
		e.setStartAge(31);
		e.setEndAge(35);

		List<UserInfo> list = um.find3(e);
		for (UserInfo ui : list) {
			System.out.println(ui);
		}
		// 提交或者回滚事务
		session.commit();
		// 关闭会话
		session.close();
	}

	public void d() {
		// 加载配置文件信息
		InputStream in = Test.class.getClassLoader().getResourceAsStream("config.xml");
		// 创建会话工厂
		SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
		// 创建会话:CRUD 这里已经自动开启事务
		SqlSession session = ssf.openSession();
		// 通过代理,MyBatis产生UserMapper的实现类 执行相关操作
		UserMapper um = session.getMapper(UserMapper.class);

		UserInfo ui = new UserInfo();
		ui.setUserName("aaa");
		ui.setUserAge(22);
		ui.setUserSex("男");
		ui.setUserAddress("宝鸡");
		um.addUser(ui);
		session.commit();
		session.close();

	}

	public void e() {
		// 加载配置文件信息
		InputStream in = Test.class.getClassLoader().getResourceAsStream("config.xml");
		// 创建会话工厂
		SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
		// 创建会话:CRUD 这里已经自动开启事务
		SqlSession session = ssf.openSession();
		// 通过代理,MyBatis产生UserMapper的实现类 执行相关操作
		UserMapper um = session.getMapper(UserMapper.class);

		um.deleteUser(73);
		session.commit();
		session.close();

	}

	public void f() {
		// 加载配置文件信息
		InputStream in = Test.class.getClassLoader().getResourceAsStream("config.xml");
		// 创建会话工厂
		SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
		// 创建会话:CRUD 这里已经自动开启事务
		SqlSession session = ssf.openSession();
		// 通过代理,MyBatis产生UserMapper的实现类 执行相关操作
		UserMapper um = session.getMapper(UserMapper.class);

		UserInfo ui = new UserInfo();
		ui.setUserName("王王王");
		ui.setUserId(64);

		um.updateUser(ui);

		session.commit();
		session.close();

	}

	Scanner in = new Scanner(System.in);
	UserBiz ub = new UserBiz();

	public void h() {//分页查询
		System.out.print("请输入页数:");
		int page = in.nextInt();
		System.out.print("请输入每页显示条数:");
		int number = in.nextInt();
		PageInfo pi = new PageInfo();
		pi.setNumber(number);
		pi.setPage(page);
		List<UserInfo> list = ub.findPage(pi);
		for (UserInfo ui : list) {
			System.out.println(ui);
		}
		ub.showMsg(pi);

		h();

	}

	public static void main(String[] args) {
		new Test().h();
	}

}

 

 

本文地址:https://blog.csdn.net/zuo_h_dr/article/details/85727300