(二)第一个mybatis项目
1. 引包
- 本例中使用maven构造项目,所以只需配置依赖即可引相应的包。
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.shyrolk</groupId> <artifactId>firstMybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>firstMybatis</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.6</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> </project>
2. 编写mybatis总配置文件mybatis-config.xml和log4j.properties
<?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?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC" /> <property name="username" value="root" /> <property name="password" value="" /> </dataSource> </environment> </environments> </configuration>
log4j.properties:
# Global logging configuration\uff0c\u5efa\u8bae\u5f00\u53d1\u73af\u5883\u4e2d\u8981\u7528debug
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
- 开发环境中建议rootLogger=DEBUG
1.3 创建数据库和实体
1.3.1 创建数据库
1.3.2 创建实体对象
package com.shyroke.entity;
public class User {
private int id;
private String userName;
private String passWord;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", passWord=" + passWord + "]";
}
}
1.5 编写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="test"> <!-- 根据 id 查询 user 表中的数据 id:唯一标识符,此文件中的id值不能重复 resultType:返回值类型,一条数据库记录也就对应实体类的一个对象 parameterType:参数类型,也就是查询条件的类型 --> <select id="findUserById" resultType="com.shyroke.entity.User" parameterType="int"> <!-- 这里和普通的sql 查询语句差不多,后面的 #{id}表示占位符,里面不一定要写id,写啥都可以,但是不要空着 --> select * from user where id = #{id} </select> <!-- 模糊查询 --> <select id="findUserByName" resultType="com.shyroke.entity.User" parameterType="java.lang.String"> select * from user where userName like '%${_parameter}%' </select> </mapper>
-
1. 如果仅传入一个类型为String的参数,那么在 xml文件中应该使用_parameter来代替参数名。
-
2. '%${_parameter}%' 这里只能用${} 而不能用#{},如果用#{},因为#{}相当于占位符?, sql语句就为like '%${?}%' 中占位符?被单引号所包围,此时?会被作为参数传入,而不会传真正的参数传入。
-
3. #{} 和${}区别: 当使用#时变量是占位符,就是一般我们使用java jdbc的PrepareStatement时的占位符?,所有可以防止sql注入 当使用$时,变量就是直接追加在sql中,一般会有sql注入问题。
1.6 加载UserMapper.xml文件
- 在mybatis的总配置文件mybatis-config.xml中添加
<mappers>
<mapper resource="com/shyroke/mapper/UserMapper.xml"/>
</mappers>
1.7 测试
package com.shyrolk.firstMybatis; import java.awt.image.ImageProducer; import java.io.InputStream; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.shyroke.entity.User; /** * Hello world! * */ public class App { public static void main( String[] args ) { InputStream inputStream=App.class.getClassLoader().getResourceAsStream("resource/mybatis-config.xml"); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession=sqlSessionFactory.openSession(); User user=sqlSession.selectOne("test.findUserById", 1); List<User> userList=sqlSession.selectList("test.findUserByName", "a"); System.out.println(userList); sqlSession.close(); } }
结果: