Java Novice Learning Guide【day34】---Mybatis quick start

1. Reasons for learning Mybatis

SSM框架:Spring+Springmvc+Mybatis

The code used by Java to manipulate the database through JDBC was too redundant and not concise. Every time you need to create a link, get data, and encapsulate objects...

The Mybatis framework provides automatic encapsulation of objects (detected data) or persistent objects (stored in the database, etc.)

Framework: Code written by others that can achieve some functions

ORMFramework: Object Relation MappingObject Relational Mapping Table-Mapping-Object

  • Full mapping: No need to write Sql execution statement, directly manipulate java code, for example: Hibernate
  • Semi-mapping: Mybatis needs to write Sql, but Sql is written separately in xml, separated from java code, convenient for maintenance

2、Hello Mybatis

1. Import the jar package first

  • Mybatis and dependent packages link MySql database package

2. Configure resource files

  • Establish the main configuration file: Configration.xml, responsible for configuring the database and mapping files
<?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"></properties>
	<!-- 可以配置多个环境 -->
	<environments default="development">
	<!-- 具体的数据库环境 -->
		<environment id="development">
			<transactionManager type="JDBC" />
			<!-- 数据连接池 -->
			<dataSource type="POOLED">
			<!-- value的值要注意,不要写错! -->
				<property name="driver" value="${driverClassName}" />
				<property name="url" value="${url}" />
				<property name="username" value="${username}" />
				<property name="password" value="${password}" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<!-- 需要配置映射文件 -->
		<mapper resource="cn\xxxx\domain\ProductMapper.xml" />
	</mappers>
</configuration>
  • Establish jdbc.properties: configure database related information

  • Establish the mapping file ProductMapper.xml: configure the relevant information namespace (the fully qualified name of the interface)

    ​ id (required to be consistent with the method name)

<?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">
<!-- 
		namespace: 命名空间:要求为接口的完全限定名
		id: 要求与方法名字一致
		parameterType: 接口中定义方法,参数类型传入
		resultType : 表中每一行的结果类型
		#{id}  接收方法的参数
 -->
<mapper namespace="cn.xxxx.dao.IProductDao">
	<select id="findOne" parameterType="long" resultType="cn.xxxx.domain.Product">
		select * from Blog where id = #{id}
	</select>
</mapper>

3. Supplement the code of the interface implementation class in dao

Write only one method for testing

@Override
	public Product findOne(Long id) {
    
    
		String resource = "Configration.xml"; 
		Reader reader;
		try {
    
    
			//读取配置文件
			reader = Resources.getResourceAsReader(resource);
			//SqlSession的工厂
			SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
			//session: 连接对象
			SqlSession session = factory.openSession();
			/**
			 * 映射文件ProductMapper.xml
			 * 参数1:namespace+id
			 * 参数2:方法传入的id
			 *               该方法查询用的是ProductMapper.xml映射关系
			 */
			Product product = session.selectOne("cn.xxxx.dao.IProductDao.findOne", id);
			return product;					     
		} catch (IOException e) {
    
    
			e.printStackTrace();
		} catch (Exception e) {
    
    
			e.printStackTrace();
		} 
		return null;
	}

4. Write unit tests

3、MybatisUtil

Extract the repetitive part of the above code and use the singleton pattern enumeration to construct MybatisUtil

/**
 * @author 53187
 * 对重复代码进行抽取
 */
public enum MybatisUtil {
    
    
	//定义一个枚举的对象
	INSTANCE;
	//声明一个工厂,只需要一个工厂,在每次加载的时候创建一次
	private static SqlSessionFactory factory = null;
	static {
    
    
		try {
    
    
			factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("Configration.xml"));
		} catch (IOException e) {
    
    
			e.printStackTrace();
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}
	//获到SqlSession对象
	public SqlSession session(){
    
    
		return factory.openSession();
	}
}

Supplementary CRUD

4. Mapper mapping manager

1. Create a new Mapper package

2. Create a new ProductMapper.java interface under the package

3. Configure the ProductMapper.xml mapping file

5. Configure aliases and set logs

1. Configure alias: It is too troublesome to simplify the fully qualified name in the main configuration file

<typeAliases>xxx
		<!-- 单个配置:测试时使用 -->
		<typeAlias type="cn.xxxx.domain.Dept" alias="Dept" />
		<!-- 包的配置:项目中使用,添加了包之后,类名或类名首字母小写就是别名 -->
		<package name="cn.xxxx.domain" />
</typeAliases>

2. Set the log

Some content printed during the execution of the program

Guess you like

Origin blog.csdn.net/WLK0423/article/details/110846858