• 周四. 12月 1st, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Mybatis learning 01: using mybatis to query database

[db:作者]

1月 6, 2022

adopt mybatis To operate mysql The steps of database can be divided into the following steps :

ad locum , Let’s take the following table as an example :
Table name :ssm
image

1 Configuration dependency

stay pom.xml Add the required dependencies to the

<!-- mybatis Core dependence -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!-- mysql drive -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- For testing purposes , We also add test unit dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- To facilitate the construction of classes , add to lomnok rely on -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
<scope>provided</scope>
</dependency>
<!-- stay build The following configuration is carried out in -->
<resources>
<resource>
<directory>src/main/java</directory><!-- The directory of the results -->
<includes><!-- Including... In the directory .properties,.xml All the files will be scanned -->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>

For operational databases , We have to maven Zhongba mybatis.xml This configuration file makes some assignments

<?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>
<!--settings: control mybatis Global behavior -->
<settings>
<!-- Set up mybatis Output log -->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<environments default="mydev">
<environment id="mydev">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- Database driver class name -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!-- Connected to the database url character string , The specific address is filled in according to your own database -->
<property name="url" value="jdbc:mysql://localhost:3306/springdb"/>
<!-- User name to access the database , It has its own database ; To fill in -->
<property name="username" value="root"/>
<!-- password , Fill in according to your own database settings -->
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- sql mapper(sql The mapping file ) The location of -->
<mappers>
<mapper resource="com/bjpowernode/dao/StudentDao.xml"/>
<!--<mapper resource="com/bjpowernode/dao/SchoolDao.xml" />-->
</mappers>
</configuration>

Note a small problem with the configuration above , If the database version is 8 above , So in the configuration database url The operation should look like this :

<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=GMT&amp;nullCatalogMeansCurrent = true"/>

If it is 8 Version below ,url The configuration is as follows

<property name="url" value="jdbc:mysql://localhost:3306/ssm Where the database is "/>

The next in src\main\java\com\bjpowernode\domain Next, create a class related to the table

@Data
public class Student {
private Integer id;
private String name;
private String email;
private Integer age;
}

After that bjpowernode\dao Next, create a new interface to operate the database

package com.bjpowernode.dao;
import com.bjpowernode.domain.Student;
import java.util.List;
public interface StudentDao {
// Here is the table selection operation
// Select data
List<Student> selectStudents();
// insert data
int insertStudent(Student student);
}

Used in this article mapper Way of agency ,

<?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 It's a namespace , The effect is to sql Carry out classified management , Understood as a sql Isolation , ad locum namesapce yes dao Under the java class , And configuration files and java The file name of the file is consistent -->
<mapper namespace="org.example.dao.StudentDao">
<!-- The sql Of the statement id,resultType It means to specify sql Output mapped java object type , The result of this operation is a student class that contains a row of database information , therefore resultType yes student Path to class -->
<select id="selectStudents" resultType="org.example.domain.student">
select *
from ssm
order by id
</select>
<!-- The insert , It only needs id, No output type is required -->
<insert id="insertStudent" >
insert into ssm value (#{id},#{name},#{email},#{age})
</insert>
</mapper>

MybatisUtils Tool class

package org.example.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MyBatisUtils {
private static SqlSessionFactory factory = null;
static {
// obtain mybatis Master profile ,
String config="mybatis.xml"; // It needs to be the same as the file name in your project
try {
// Read configuration file
InputStream in = Resources.getResourceAsStream(config);
// establish SqlSessionFactory object , The purpose is to get SqlSession
factory = new SqlSessionFactoryBuilder().build(in);
} catch (IOException e) {
e.printStackTrace();
}
}
// obtain SqlSession Methods
public static SqlSession getSqlSession() {
SqlSession sqlSession = null;
if( factory != null){
// obtain SqlSession,SqlSession Can execute sql sentence
sqlSession = factory.openSession();// Non auto commit transactions
}
return sqlSession;
}
}

After all the classes and configurations are set up, write a test class , To select the elements of sql Statements, for example

package org.example;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.example.domain.student;
import org.example.utils.MyBatisUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyApp2 {
public static void main( String[] args ) throws IOException {
// obtain SqlSession object , from SqlSessionFactory In order to get SqlSession
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//【 important 】 Specifies which to execute sql The identity of the statement . sql In the mapping file namespace + "." + Labeled id value
String sqlId = "org.example.dao.StudentDao.selectStudents";
//【 important 】 perform sql sentence , adopt sqlId Find sentences
List<student> studentList = sqlSession.selectList(sqlId);
// Output results
studentList.forEach( stu -> System.out.println(stu));
// close SqlSession object
sqlSession.close();
}
}

Output results : Subject to the data set in the database
image

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注