The most detailed zero-based dynamic web project in the whole network integrates the mybatis framework to realize addition, deletion, modification and query system (case + source code)

Environmental preparation

The environment used by this system is

  1. Eclipse
  2. jdk1.8
  3. .mysql database
  4. tomcat 8 .5
  5. Database tool: navicat

If the environment will not be configured, please move to my other article.
Eclipse builds maven projects offline, configures local warehouses, and creates mybatis projects

problem analysis

This case will make a detailed display of the product table tb_goods in the database db_goods in the product system. The design of the table is as follows:

field type length non empty illustrate
id int 11 yes primary key, auto increment
name varchar 32 yes product name
price decimal (6,2) yes commodity price
store_number int 5 yes Commodity stocks
goods_type varchar 6 yes Commodity type (physical object, virtual transaction item)
in_time datetime yes Product storage time

In this case, additions, deletions, modifications, and queries will be implemented for the data table.

accomplish

Create database, data table, add test data

open mysql service

Method 1. Use the command to open the mysql service

net start mysql

Method 2. Open from the task manager (suitable for Xiaobai)
to open the task management, find the service option, swipe down to find the mysql service, if the status shows that it is stopped, right click on the service and choose to run.
insert image description here

Connect to mysql and create a database

After the service is opened, use navicat software to connect.
insert image description here

From the problem analysis, we have analyzed that the database name is db_goods and the table name is tb_goods.
Use navicat software to create a database
insert image description here
Enter the database name, select the encoding and collation.

insert image description here
After the creation is complete, there will be an additional database in the database list column.
insert image description here

Create a data table from the design

Double-click to open the data db_goods created earlier. The color will change after opening, it is no longer gray. Then right click and select New Table.
insert image description here
Enter the design information for the table according to the design rules for the table. Among them, the id field needs to add two settings of primary key and auto-increment.
insert image description here
After the table design is complete, click Save, and enter the table name tb_goods (extracted from the question) in the pop-up input box.
insert image description here
After clicking OK, an additional table will appear in the database.
insert image description here

Add test data

Double-click the tb_goods data table to enter the preview page of the table. Click the add symbol at the bottom of the panel to add data.
insert image description here
Remarks: When entering data, since the id field is self-incrementing, there is no need to enter a value in this column.

export database script

When the data is added, the database script can be exported through the visual operation. Right-click the database to be exported, select Dump SQL file, and the type is structure and data.
insert image description here
Select the desktop as the storage location.
insert image description here
The purpose of exporting the database is to save the currently designed table and stored data content. You can import the script into the database when you need it next time, and you can use it.

project realization

Create a dynamic web project

Open Eclipse, click the toolbar in the upper left corner, and find the File option. Find the Dynamic Web Project option to create it.
insert image description here
If there is no such option, find the last Other option.
insert image description here
In the pop-up box, first find the web directory and expand it, and then you can find the Dynamic Web Project option.
insert image description here
Then click on the Next option.
Enter the project name in the pop-up box. Of course, please change other default configurations if necessary.
insert image description here
After the project is successfully created, the directory structure is shown in the figure below.
insert image description here
After the project is created, import the jar package required for this case. The corresponding introduction of each jar package is as follows

jar package illustrate
mysql-connector-java-5.1.14.jar jar package for mysql connection
mybatis-3.4.6.jar The jar package that the mybatis database framework depends on
jstl-1.2.jar jstl tag library, used in jsp pages
standard-1.1.2.jar Standard library, used with jstl tag library

Add the above four tag libraries to the project dependency directory, that is, the lib folder in Web-Info under the WebContent directory.
insert image description here
When copying in for the first time, you need to right-click to select these tags, then select Build Path and select Add to Build Path. Add these jar packages to the project build path. Otherwise, it cannot take effect in the project.

Configure mybatis

Create the mybaits-config.xml file in the src directory of the project.
insert image description here
Its configuration content is as follows:

<?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>
	<!-- 配置实体类所在的包 -->
	<typeAliases>
		<package name="com.lvan.pojo"/>
	</typeAliases>
	<environments default="devlopment">
		<environment id="devlopment">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql://localhost:3306/db_goods"/>
				<property name="username" value="root"/>
				<property name="password" value="root"/>
			</dataSource>
		</environment>
	</environments>
	<!-- 配置映射文件所在的包 -->
	<mappers>
		<package name="com.lvan.mapper"/>
	</mappers>
</configuration>

The main thing is to remember the configuration information of the two packages and the mysql connection pool.
Create the corresponding package according to the configuration file.
insert image description here
Just like the above structure.

Create entity classes based on data tables

The corresponding entity class created under the pojo package.
The class name naming rule is generally to remove the prefix of the data table, capitalize the first letter of the subsequent words, and remove the underline if there is any, and capitalize the first letter after the underline. Follow the camel case naming convention.
For example, if the entity class name of tb_goods is Goods
insert image description here
, as in this simple case, the attribute name should be consistent with the field name. But pay attention to data type compatibility.
Normally, decimal corresponds to double int, corresponds to int, and other strings can basically achieve compatibility, but it is not recommended to use String entirely.

Generate encapsulation methods in entity classes

Mr. generate setter and getter methods.
insert image description here

insert image description here
Select the Generate button below to generate.
The effect diagram is as follows.
insert image description here

Generate toString method

insert image description here
insert image description here
The effect diagram is as follows
insert image description here
At this point, the entity class is created.

interface writing

According to the mybatis-config.xml configuration file, the mapping file should be written in the com.lvan.mapper package. Note that the package tag is used to declare the scan scope as a package. If you use the mapper tag, you need to specify the corresponding mapper.xml file .
insert image description here
Under the mapper package, create an interface file.
insert image description here
The name of the interface file is the entity class name followed by Mapper as follows:
insert image description here
that is, just declare the method to be implemented in the interface file.
According to the requirements, in this case, it is necessary to add, delete, modify and query the product table. Therefore, the interface for querying product declarations is as follows:
insert image description here
The following is an example of the interface:

  1. Query products are searched according to keywords. If the content of the query is an empty character, then it is all queries
List<Goods> query(@Param("key")String key);
  1. To update a product, if you want to update a product, use the entity class object to update, that is, which fields of the table will be changed according to which attributes the entity class object has
int updateGoods(Goods goods);
  1. Adding a product Adding a product also requires an entity class object to be added, and the attribute of the object is used to obtain the value in the sql statement
int addGoods(Goods goods);
  1. Deleting a product Deleting a product is based on the id, that is, deleting the data record with the specified number
int deleteGoods(@Param("id")String id);
  1. Get the corresponding entity object according to the id, and you can echo the product information to the page when editing the product
Goods getGoodsById(@Param("id")String id);

The code structure is as follows:
insert image description here
That is to say, after the above interface declaration is completed, the management of the product table can basically be realized.

Mapping file writing

In the above tutorial, the corresponding interface has been written according to the needs of the case. The content of this section is to implement the above interfaces one by one.

  1. Create a mapping file corresponding to the interface, the suffix name is .xml,
    and its content is roughly as follows:
<?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="xxx.xxx.XXXMapper">

</mapper>

Note: The file name needs to be consistent with the interface file name, otherwise there will be problems such as incompatibility.
2. Bind the namespace
It is necessary to keep the file names of the interface file and the mapping file consistent, which can be understood as wearing couple clothes.
insert image description here
3. Realize the
implementation of the interface query interface
insert image description here
The implementation code is as follows:

<?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文件就是对应的男朋友,女朋友负责吩咐,男朋友负责做事-->
<mapper namespace="com.lvan.mapper.GoodsMapper">
	<!-- 查询 -->
	<select id="query" resultType="Goods">
		select * from tb_goods where name like concat('%',#{key},'%')
	</select>
</mapper>

Implementation of the update interface :
insert image description here
The code for the update interface is as follows:

	<!-- 更新商品的实现-->
	<update id="updateGoods">
		update tb_goods set
		<if test="name!=null">
			name=#{name},
		</if>
		<if test="price!=0.0">
			price=#{price},
		</if>
		<if test="store_number!=0">
			store_number=#{store_number},
		</if>
		<if test="goods_type!=null">
			goods_type=#{goods_type},
		</if>
		<if test="in_time!=null">
			in_time=#{in_time},
		</if>
		id=#{id}
		where id=#{id}
	</update>

Add the implementation of the interface :
insert image description here
the specific implementation code is as follows:

	<!-- 添加商品 -->
	<insert id="addGoods">
		insert int tb_goods(name,price,store_number,goods_type,in_time)
		values (#{name},#{price},#{store_number},#{goods_type},now())
	</insert>
  1. Delete interface implementation
    insert image description here
    The implementation code is as follows:
<delete id="deleteGoods">
		delete from tb_goods where id=#{id}
</delete>
  1. Obtain the specified product interface implementation based on the id.insert image description here
    The code is implemented as follows:
<!-- 获取指定id的商品 -->
	<select id="getGoodsById" resultType="Goods">
		select * from tb_goods where id=#{id}
	</select>

The interface implemented by the test

  1. Write the SqlUtil toolkit
    Create a com.lvan.util package and create a test class
    insert image description here
  2. Write the tool class required for testing.
    insert image description here
    The implementation code is as follows:
package com.lvan.util;

import java.io.Reader;

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

public class SqlUtil {
	//1.声明静态的SqlSession对象 用于获取mysql连接
	public static SqlSession sqlSession;
	static {
		try {
			//2.读取mybatis配置文件 
			Reader reader=Resources.getResourceAsReader("mybatis-config.xml");
			//3.根据配置对象生成对应的工厂对象 
			SqlSessionFactory sf=new SqlSessionFactoryBuilder().build(reader);
			//4.打开连接
			sqlSession=sf.openSession();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		System.out.println(sqlSession);
	}
}
  1. Write test cases
    Create test packages, write test classes,
    insert image description here
    test and query all commodity objects
    insert image description here
package com.lvan.test;

import java.util.List;

import com.lvan.mapper.GoodsMapper;
import com.lvan.pojo.Goods;
import com.lvan.util.SqlUtil;

public class Test {
	public static void main(String[] args) {
		//获取接口对象 代理对象
		GoodsMapper goodsMapper=SqlUtil.sqlSession.getMapper(GoodsMapper.class);
		List<Goods> goods=goodsMapper.query("");//传递空值 查询所有
		System.out.println("查询全部:"+goods);
	}
}

The running screenshot is as follows:
insert image description here
The search function test case is as follows:

GoodsMapper goodsMapper=SqlUtil.sqlSession.getMapper(GoodsMapper.class);
		List<Goods> goods=goodsMapper.query("Q");//传递空值 查询所有
		System.out.println("关键词查询:"+goods);

The running results are as follows:
insert image description here
Other functions are no longer tested, and the testers write test cases according to the interface requirements.

Realize the page

Description: Use an IndexServlet to implement, different functions are distinguished by the parameter action

First create a package named com.lvan.servlet and create an IndexServlet under the package
insert image description here

insert image description here

Delete other unnecessary methods and only keep one doGet method

insert image description here

Home page content rendering

  1. Realize the function of jumping to the home page
    Implementation steps:
    1.1 Define the global proxy object,
    insert image description here
    set the coding rules and response type
    insert image description here
//设置编码规则
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		//设置响应的内容类型
		response.setContentType("text/html");

1.1 If the action parameter does not exist, it means go to the homepage
insert image description here
1.2 Write the page
Create an index.jsp page in the Web-content directory
insert image description here

insert image description here
Change the coding rules:
insert image description here
Change to the following.
insert image description here
Write the table tag, and the user renders the data according to the attribute of the entity class to declare the corresponding table header and operation column.
insert image description here
Before rendering the data, you need to import the tag library required by the c:foreach tag,
insert image description here
insert image description here
so that the page data is realized. The rendering
effect diagram is as follows:
insert image description here
1.3 Realization of search function
Definition: The input action value is search, which means that the search search can be customized.
insert image description here
Add a search bar in front of the table and the content is as follows.
insert image description here
The test results are as follows:
insert image description here
1.4 Delete operation
insert image description here
Add a delete button to the page and note that the request path is /project name/service name
insert image description here
Test:
Click the item numbered 4 to
insert image description here
return to the home page to refresh
insert image description here

Guess you like

Origin blog.csdn.net/qq_33183456/article/details/123539885