mybatis framework project references 1

Mybatis Quick Start
Mybatis introduce
MyBatis persistence framework is to support outstanding ordinary SQL queries, stored procedures and advanced mappings. MyBatis eliminates almost all of the code and to manually set parameters JDBC package and retrieve the result set. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJO (Plain Old Java Objects, ordinary Java objects) is mapped to the number of records in the library MyBatis-Hibernate .JDBC-
2.2 Mybatis environment to build
add Maven coordinates

<dependencies>
	<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
	<dependency>
		<groupId>org.mybatis</groupId>
		<artifactId>mybatis</artifactId>
		<version>3.4.4</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.21</version>
	</dependency>
</dependencies>

To build the table

	CREATE TABLE users(
	id INT PRIMARY KEY AUTO_INCREMENT, 
	NAME VARCHAR(20), 
	age INT);
	INSERT INTO users(NAME, age) VALUES('Tom', 12);
	INSERT INTO users(NAME, age) VALUES('Jack', 11);

Add mybatis profile

  <?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>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/test" />
				<property name="username" value="root" />
				<property name="password" value="root" />
			</dataSource>
		</environment>
	</environments>
</configuration>

Entity class definition table

		   package com.entity;
		 public class User {
			private int id;
			private String name;
			private int age;
		    //get,set方法
		}

Interface definitions userMapper

	package com.itmayiedu.mapper;
	import com.itmayiedu.entity.User;
	public interface UserMapper {
		public User getUser(int id);
	}

Sql operation defined users table mapping file userMapper.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="com.itmayiedu.mapper.UserMapper">
	<select id="getUser" parameterType="int" resultType="com.itmayiedu.entity.User">
		SELECT *
		FROM users where id =#{id}
	</select>
</mapper>

mybatis.xml file to load the configuration file

<mappers>
<mapper resource="mapper/userMapper.xml" />
</mappers>

mybatis.xml test methods

	import java.io.File;
	import java.io.IOException;
	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;
	import com.itmayiedu.entity.User;
	public class TestMybatis {
		public static void main(String[] args) throws IOException {
			String resource = "mybatis.xml";
			// 读取配置文件
			Reader reader = Resources.getResourceAsReader(resource);
			// 获取会话工厂
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
			SqlSession openSession = sqlSessionFactory.openSession();
			// 查询
			String sql = "com.itmayiedu.mapper.UserMapper.getUser";
			// 调用api查询
			User user = openSession.selectOne(sql, 1);
			System.out.println(user.toString());
		}
	}

sql injection case

The first: username = 'OR 1 = 1 - or username or 1 =' 1
second: sql Comment - Comment represented SQL, thus ignoring end of the statement;
sql injection solution
precompiled sql statement

     String username = "username='  OR 1=1 -- ";
	String password = "12345";
	// String sql = "SELECT id,username FROM user_table WHERE " +
	// "username='" + username + "'AND " + "password='"
	// + password + "'";
	String sql = "SELECT id,username FROM user_table WHERE username=? AND password=?";
	Class.forName("com.mysql.jdbc.Driver");
	Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
	PreparedStatement stat = con.prepareStatement(sql);
	stat.setString(1, username);
	stat.setString(2, password);
	System.out.println(stat.toString());
	ResultSet rs = stat.executeQuery();
	while (rs.next()) {
		String id = rs.getString(1);
		String name = rs.getString(2);
		System.out.println("id:" + id + "---name:" + name);
	}

mybatis the difference between # and $

But $ # {} and {} is processed in the pre-compiler is not the same. # {} While pretreatment parameters will part with a placeholder? Place, while $ {} string is simply replaced, the dynamic resolution phase, the sql statement is parsed into
the above, the # {} parameter substitution occurs in the DBMS, and {} $ occurs in the dynamic resolution process.
Here Insert Picture Description
Priority use#{}. Because $ {} sql injection causes problems of

Mybatis use annotations

Mybatis provides CRUD annotation, @ select @delete @update

Generator Use

Generator generated using reverse
profile:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
	<!-- 数据库驱动包位置 -->
	<!-- <classPathEntry location="D:\software\lib\mysql-connector-java-5.1.21.jar" /> -->
	<classPathEntry location="C:\oracle\product\10.2.0\db_1\jdbc\lib\ojdbc14.jar" />
	<context id="DB2Tables" targetRuntime="MyBatis3">
		<commentGenerator>
			<property name="suppressAllComments" value="true" />
		</commentGenerator>
		<!-- 数据库链接URL、用户名、密码 -->
		<!-- <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/sy" userId="sypro" password="sypro"> -->
		<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@localhost:1521:orcl" userId="msa" password="msa">
		</jdbcConnection>
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>
		<!-- 生成模型的包名和位置 -->
		<javaModelGenerator targetPackage="sy.model" targetProject="D:\study\mybatis\src">
			<property name="enableSubPackages" value="true" />
			<property name="trimStrings" value="true" />
		</javaModelGenerator>
		<!-- 生成的映射文件包名和位置 -->
		<sqlMapGenerator targetPackage="sy.mapping" targetProject="D:\study\mybatis\src">
			<property name="enableSubPackages" value="true" />
		</sqlMapGenerator>
		<!-- 生成DAO的包名和位置 -->
		<javaClientGenerator type="XMLMAPPER" targetPackage="sy.dao" targetProject="D:\study\mybatis\src">
			<property name="enableSubPackages" value="true" />
		</javaClientGenerator>
		<!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
		<table tableName="tbug" domainObjectName="Bug" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
</generatorConfiguration>

cmd生成命令:
java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite

Required jar package:
the mybatis-Generator-Core-1.3.2.jar

Published 32 original articles · won praise 0 · Views 2404

Guess you like

Origin blog.csdn.net/YHM_MM/article/details/104088009