Create MyBatis project in Eclipse

1. Create MyBatis project

To create a Maven Project, use cn.tedu.mybatis for Group Id, MyBatis for Artifact Id, and war for Packaing (you can also choose jar).

After the project is created, you need to: generate a web.xml file; add dependencies in pom.xml; copy spring-mvc.xml from the previous project to the current project; add the Tomcat operating environment (this case may not be needed); open the previous In the web.xml of the project, copy the configuration of DispatcherServlet and CharacterEncodingFilter to the current project.

This time you need to add dependencies:

<!-- MyBatis -->
<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis</artifactId>
	<version>3.5.1</version>
</dependency>

<!-- MyBatis整合Spring -->
<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis-spring</artifactId>
	<version>2.0.1</version>
</dependency>

<!-- SpringJDBC -->
<!-- 注意:与当前项目使用的其它spring依赖保持相同的版本号 -->
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-jdbc</artifactId>
	<version>4.3.10.RELEASE</version>
</dependency>

<!-- mysql连接 -->
<!-- 可选版本号:8.0.12~8.0.16,5.1.4~5.1.6 -->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>8.0.16</version>
</dependency>

<!-- 数据库连接池 -->
<dependency>
	<groupId>commons-dbcp</groupId>
	<artifactId>commons-dbcp</artifactId>
	<version>1.4</version>
</dependency>

<!-- 单元测试 -->
<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.12</version>
</dependency>

Then, copy spring-mvc.xml to get spring-dao.xml, delete the configuration in spring-dao.xml file!

2. Database connection

Create a db.properties file under src/main/resources to configure related information about the database connection:

url=jdbc:mysql://localhost:3306/tedu_ums?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
driver=com.mysql.cj.jdbc.Driver
username=root
password=root
initialSize=2
maxActive=10

When configuring the driver attribute, you need to pay attention to the version of mysql-connector-java used. If you are using version 5.x, the attribute value should be com.mysql.jdbc.Driver, if you are using 6.x or higher Version, the attribute value should be com.mysql.cj.jdbc.Driver, if you are not sure which value should be used, you can expand the jar file of mysql-connector-java to observe! In addition, there is a META-INF/services/java.sql.Driver file in the jar package, which records the Driver class that should be used when using the jar package.

If you are using mysql-connector-java of version 6.x or above, you must explicitly set the value of the serverTimezone parameter when configuring the URL to connect to the database! Available values ​​in Mainland China are Asia/Shanghai and Asia/Chongqing.

Need to add configuration in spring-dao.xml, read the configuration information in the above db.properties:

<util:properties id="config" location="classpath:db.properties" />

Then, when connecting to the database, the data source used will be BasicDataSource, you need to inject the database connection information read above into the properties of BasicDataSource:

<!-- 配置数据源,保证其能够连接数据库 -->
<bean id="dataSource"
	class="org.apache.commons.dbcp.BasicDataSource">
	<property name="url" value="#{config.url}" />
	<property name="driverClassName" value="#{config.driver}" />
	<property name="username" value="#{config.username}" />
	<property name="password" value="#{config.password}" />
	<property name="initialSize" value="#{config.initialSize}" />
	<property name="maxActive" value="#{config.maxActive}" />
</bean>

Then, you can write and execute unit tests in the test class to check whether the configuration is correct:

public class Tests {
	
	ClassPathXmlApplicationContext ac;
	
	@Before
	public void doBefore() {
		ac = new ClassPathXmlApplicationContext(
				"spring-dao.xml");
	}
	
	@After
	public void doAfter() {
		ac.close();
	}
	
	@Test
	public void getConnection() throws SQLException {
		BasicDataSource dataSource = ac.getBean("dataSource", BasicDataSource.class);
		Connection conn = dataSource.getConnection();
		System.out.println(conn);
	}

}

3. Interfaces and abstract methods

Tentative goal: Use MyBatis to insert new user data into the data table.

When using MyBatis, you need to define the abstract methods corresponding to each function, and these abstract methods must be defined in the interface!

First, you should create the cn.tedu.mybatis.UserMapper interface file, and then define the abstract method of "inserting user data" in the interface. The design principle of the abstract method:

  • If you need to perform an operation of adding, deleting, or modifying types, use Integer as the return value of the method, which will indicate the "number of rows affected", which can be used to judge the success of the operation, or it can be designed as an int, or it can be designed Void means don't care about the number of rows affected;
  • The method name can be customized and cannot be overloaded;
  • The parameter list is determined according to the required parameters. You can refer to the question marks in SQL when learning JDBC before, and write which parameters.

The SQL statement that needs to be executed for "insert user data" is roughly:

insert into (username, password, age, phone, email) values (?,?,?,?,?)

The abstract method needs to write 5 parameters. If more fields are added to the data table later, more parameters need to be written. This approach is flawed. These parameters should be encapsulated in the cn.tedu.mybatis.User class. in:

public class User {

	private Integer id;
	private String username;
	private String password;
	private Integer age;
	private String phone;
	private String email;

}

The abstract method can be designed as:

Integer insert(User user);

Next, you need to configure "Where is the interface file" to ensure that the interface can be found when the MyBatis framework works:

<!-- 配置MapperScannerConfigurer -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	<!-- 配置接口文件在哪里 -->
	<property name="basePackage"
		value="cn.tedu.mybatis" />
</bean>
  1. Configure SQL mapping

Download the XML file compression package for writing configuration files.

Create a folder named mappers under src/main/resources and copy SomeMapper.xml in the compressed package to this folder.

Note: The XML file used to configure SQL statements in MyBatis must include the following statement, otherwise it will not work properly!

<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

When configuring the XML file, first, you need to add a root node, and you must configure the namespace attribute. The attribute value indicates which interface file corresponds to:

<!-- namespace:对应哪个接口 -->
<mapper namespace="cn.tedu.mybatis.UserMapper">

</mapper>

Then, according to the type of SQL statement that needs to be executed, select the child node from,,, and. The id attribute of the node is the name of the abstract method. Then, write the SQL statement that needs to be executed in the content of the node. Use #{} in the parameter part. Format placeholder, the name inside the placeholder is the attribute name in the method parameter User class:

<!-- id:抽象方法的名称 -->
<insert id="insert">
	INSERT INTO t_user (
		username, password, 
		age, phone, 
		email
	) VALUES (
		#{username}, #{password},
		#{age}, #{phone},
		#{email}
	)
</insert>

Then, you need to configure "Where is the XML file" and "Which data source is used to connect to the database" when the framework is executed! Therefore, you need to add configuration in spring-dao.xml:

<!-- 配置SqlSessionFactoryBean -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
	<!-- 配置XML文件在哪里 -->
	<property name="mapperLocations" 
		value="classpath:mappers/*.xml" />
	<!-- 配置使用哪个数据源连接数据库 -->
	<property name="dataSource"
		ref="dataSource" />
</bean>

Finally, write and execute unit tests:

@Test
public void insert() {
	User user = new User();
	user.setUsername("zhaoqi");
	user.setPassword("888999");
	user.setPhone("010-88888888");
	Integer rows = userMapper.insert(user);
	System.out.println("rows=" + rows);
}

Guess you like

Origin blog.csdn.net/qq_37669050/article/details/102403362