J2EE basics

1. Create a project
2. Add jar package

Insert picture description here
After clicking, click Add External JARs on the right to add all the packages in this folder in the j2ee folder
Insert picture description here
and then click Add Library to add the JRE System Library library.
After finishing it, there will be one, even if it is successful.
Insert picture description here
Step 3: log4j.properties
1. In src nnew A File copy log4j.properties into it as a name, and
Insert picture description here
code in this file

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

Mybatis uses log4j as the output log information by default.
The fourth step: SqlMapConfig.xml
in src nnew a File, copy SqlMapConfig.xml into it and make the name The
code 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>
	<!-- 和spring整合后 environments配置将废除-->
	<environments default="development">
		<environment id="development">
		<!-- 使用jdbc事务管理-->
			<transactionManager type="JDBC" />
		<!-- 数据库连接池-->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/mysql?characterEncoding=utf-8" />
				<property name="username" value="root" />
				<property name="password" value="" />
			</dataSource>
		</environment>
	</environments>
	
</configuration>

SqlMapConfig.xml is the core configuration file of mybatis. The configuration content of the above file is data source and transaction management.
Five: po class
Class specification:
class mapping to class
Catalog mapping to catalog table one-to-one
1. A new package in src, named cn.qziedu.po
Insert picture description here
2. A new class named Catalog in the cn.qziedu.po package
3. Create a table catalog in the database, and then the type in the table should be consistent
with the data in the catalog 4. The data in the catalog

package cn.qziedu.po;
/**
 * 
 * @author 14643
 *@desc
 *私有属性和get set方法
 */
public class Catalog {
    
    
	private Integer id;//编号
	private String title;//分类名称
	private String parent_id;//父编号
	public Integer getId() {
    
    
		return id;
	}
	public void setId(Integer id) {
    
    
		this.id = id;
	}
	public String getTitle() {
    
    
		return title;
	}
	public void setTitle(String title) {
    
    
		this.title = title;
	}
	public String getParent_id() {
    
    
		return parent_id;
	}
	public void setParent_id(String parent_id) {
    
    
		this.parent_id = parent_id;
	}
	@Override
	public String toString() {
    
    //第二个快捷方式创建
		return "Catalog [id=" + id + ", title=" + title + ", parent_id=" + parent_id + "]";
	}
}

After typing, press this to create a shortcut.
Insert picture description here
Press the following to create additional codes that you need
Insert picture description here

6. Write the program
1. Create a Folder named sqlmap in scr
Insert picture description here
2. Create a File named Catalogs.xml in the sqlmap folder;
first add the main statement in Catalogs.xml:

<?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="test">
</mapper>

Add the search code in the main statement:
parameterType: defines the mapping type input to sql, #{id} means using preparedstatement to set placeholders and pass the input variable id to sql.
resultType: Define the result mapping type.

<!-- 查询catalog的id获取catalog信息 -->
<!-- 增删改查insert,delete.update,select -->

<!-- parameterType="int" 输入参数-->

<!-- 
	resultType="cn.qziedu.po.Catalogs"输出参数
	参数类型:cn.qziedu.po.Catalogs包名+类名
 -->
 <!-- 根据id获取用户信息 -->
	<select id="findCatalogById" parameterType="int" resultType="cn.qziedu.po.Catalog">
		select * from catalog where id=#{
    
    id}
	</select>
	<!-- 自定义条件查询用户列表 -->
	<select id="findCatalogsByIdTitle" parameterType="string" resultType="cn.qziedu.po.Catalog">
		select * from catalog where title like '%${value}%'
	</select>

3.1.6.7.1.2 Load the mapping file:
Mybatis framework needs to load the mapping file,
add in SqlMapConfig.xml:

<mappers>
	<mapper resource="sqlmap/Catalogs.xml"/>
</mappers>

The test program
new has a package named cn.qziedu.test
and a new JUnit Test Case named TestCatalog in cn.qziedu.test. Before creating it, check the setUp() option below, and then change it to the following to run successfully

package cn.qziedu;

import static org.junit.jupiter.api.Assertions.*;

import java.io.InputStream;

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.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import cn.qziedu.po.Catalog;

class TestCatalog {
    
    
	//1.配置环境SqlMapConfig.xml+Catalogs.xml
	//2.通过配置文件生成SqlSessionDactory
	private SqlSessionFactory sqlSessionFactory;

	@BeforeEach
	void creatSqlSessionFactory() throws Exception {
    
    
		// 配置文件
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);

		// 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	}
	// 根据 id查询用户信息
	@Test
	void testFindCatalogById() {
    
    
		SqlSession sqlsession=null;
		try {
    
    
			// 创建数据库会话实例sqlSession
		sqlsession=sqlSessionFactory.openSession();
		// 查询单个记录,根据用户id查询用户信息
		Catalog catalog= sqlsession.selectOne("test.findCatalogById",2);
		// 输出用户信息
					System.out.println(catalog);
		}catch(Exception e) {
    
    
			e.printStackTrace();
		}finally {
    
    
			if (sqlsession != null) {
    
    
				//关闭sqlsession
				sqlsession.close();
			}
		}
	}

}

So even if the query is successful,
fuzzy query

//模糊查询
	void testFindCatalogByTitle() {
    
    
		SqlSession sqlsession=null;
		try {
    
    
			sqlsession=sqlSessionFactory.openSession();
			List<Catalog> catalog=sqlsession.selectList("test.findCatalogByTitle","X");
			System.out.println(catalog.size());
		}catch(Exception e) {
    
    
			e.printStackTrace();
		}finally {
    
    
			if (sqlsession != null) {
    
    
				//关闭sqlsession
				sqlsession.close();
			}
		}
	}

parameterType and resultType
parameterType: specify the input parameter type, mybatis obtains the parameter value from the input object through ognl and splices it in SQL.
resultType: Specify the output result type, mybatis maps a row of record data of the sql query result to an object of the type specified by resultType.

Query all:
add in Catalog.xml

<select id="findAll" resultType="cn.qziedu.po.Catalog">
 		select * from catalog where 1=1
</select>

Then add in the TestCatalog.java test side

@Test
	//类名:首字母大写
	//类方法名称:驼峰
	void testfindAll() {
    
    
		SqlSession sqlsession=null;
		try {
    
    
			sqlsession=sqlSessionFactory.openSession();
			List<Catalog> catalog=sqlsession.selectList("test.findAll");
			System.out.println(catalog.size());
		}catch(Exception e) {
    
    
			e.printStackTrace();
		}finally {
    
    
			if (sqlsession != null) {
    
    
				//关闭sqlsession
				sqlsession.close();
			}
		}
	}

These two are corresponding

Insert data
1. First add in Catalog.xml


	<!-- 简单类型是单个,比较简单,多个怎么处理 -->
	<!-- 插入的SQL语句 -->
	<insert id="insertCatalog" parameterType="cn.qziedu.po.Catalog">
	<!-- 也可以不用写selectKey这个东西 -->
		<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
			select LAST_INSERT_ID()
		</selectKey>
	
		insert into catalog (title,parent_id)values (#{
    
    title},#{
    
    parent_id})
	</insert>
	

2. Then add in TestCatalog


	
	//插入
	@Test
	void testInsertCatalog() {
    
    
		SqlSession sqlsession=null;
		try {
    
    
			// 数据库会话实例
			sqlsession=sqlSessionFactory.openSession();
			// 添加用户信息
			Catalog catalog=new Catalog();
			catalog.setTitle("xx");
			catalog.setParent_id("0");
			sqlsession.insert("test.insertCatalog",catalog);
			//提交事务,要提交事务,没有提交的话没有执行,表格不会出现数据
			//数组一致性,原子性,完整性
			//插入、删除、跟新有问题,他会rollback回滚回来之前的模样
			//insert的第一个参数是映射文件的namespace+id=test.insertCatalog
			Integer i=sqlsession.insert("test.insertCatalog",catalog);
			sqlsession.commit();//凡是增删改都要加这一句
			System.out.println("insert"+catalog.getId());//用err打印出来的事红色的,out出来的是黑色的
		}catch(Exception e) {
    
    
			e.printStackTrace();
		}finally {
    
    
			if (sqlsession != null) {
    
    
				//关闭sqlsession
				sqlsession.close();
			}
		}
	}

Delete data
1. First add in Catalog.xml

	<!-- 删除 -->
	<delete id="deleteCatalogById" parameterType="int">
		delete from catalog where id=#{
    
    id}
	</delete>

2. Then add in TestCatalog


	//删除
	@Test
	void testDeleteCatalogById() {
    
    
		SqlSession sqlsession=null;
		try {
    
    
			// 数据库会话实例
			sqlsession=sqlSessionFactory.openSession();
			Integer i=sqlsession.delete("test.deleteCatalogById",18);
			sqlsession.commit();//凡是增删改都要加这一句
		}catch(Exception e) {
    
    
			e.printStackTrace();
		}finally {
    
    
			if (sqlsession != null) {
    
    
				//关闭sqlsession
				sqlsession.close();
			}
		}
	}
	

Modify data
1. First add in Catalog.xml


	<!-- 修改 -->
	<update id="updateCatalog" parameterType="cn.qziedu.po.Catalog">
		update catalog set title=#{
    
    title},parent_id=#{
    
    parent_id} where id=#{
    
    id}
	</update>

2. Then add in TestCatalog

//修改
	@Test
	void testUpdatetCatalog() {
    
    
		SqlSession sqlsession=null;
		try {
    
    
			// 数据库会话实例
			sqlsession=sqlSessionFactory.openSession();
			// 添加用户信息
			Catalog catalog=new Catalog();
			catalog.setTitle("aa");
			catalog.setParent_id("0");
			catalog.setId(11);
			
			Integer i=sqlsession.insert("test.updateCatalog",catalog);
			sqlsession.commit();//凡是增删改都要加这一句
			System.err.println("insert"+catalog.getId());//用err打印出来的事红色的,out出来的是黑色的
		}catch(Exception e) {
    
    
			e.printStackTrace();
		}finally {
    
    
			if (sqlsession != null) {
    
    
				//关闭sqlsession
				sqlsession.close();
			}
		}
	}

Guess you like

Origin blog.csdn.net/weixin_44931166/article/details/104542905