前置知识
配置JDK1.8
运行环境: ubuntu x64
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 解压到/opt下 sudo tar -zxvf jdk-8u181-linux-x64.tar.gz -C /opt
配置全局环境变量 sudo vim /etc/profile export JAVA_HOME=/opt/jdk1.8.0_331 export CLASSPATH=.:$JAVA_HOME/lib:$JAVA_HOME/jre/lib export PATH=$JAVA_HOME/bin:$PATH
使环境变量生效 source /etc/profile
验证是否安装成功 java -version
|
JDBC
是java用于数据库连接的标准API
JDBC连接数据库示例代码如下:
1 2 3 4 5 6 7
| String CLASS_NAME = "com.mysql.jdbc.Driver"; String URL = "jdbc:mysql://localhost:3306/mysql" String USERNAME = "root"; String PASSWORD = "root";
Class.forName(CLASS_NAME); Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
|
Maven
项目架构管理工具,自动导入jar包
安装
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 解压到/opt下 sudo tar -zxvf apache-maven-3.8.5-bin.tar.gz -C /opt
配置全局环境变量 sudo vim /etc/profile export MAVEN_HOME=/opt/apache-maven-3.8.5 export M2_HOME=$MAVEN_HOME/bin export PATH=$MAVEN_HOME/bin:$PATH
使环境变量生效 source /etc/profile
验证是否安装成功 mvn -v
|
配置阿里云镜像
1 2 3 4 5 6
| <mirror> <id>aliyunmaven</id> <mirrorOf>*</mirrorOf> <name>阿里云公共仓库</name> <url>https://maven.aliyun.com/repository/public</url> </mirror>
|
设置本地仓库
1 2
| 在maven文件夹下新建文件夹maven-repo并打开配置文件 <localRepository>/opt/apache-maven-3.8.5/maven-repo</localRepository>
|
使用maven创建web项目
直接从官网抄过来改改
1
| mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
|
缩写“GAV”:groupId、artifactId、version
groupId是域名倒着写,artifactId是项目名,archetypeArtifactId是要使用的maven模板,这里用webapp来的模板
1
| mvn archetype:generate -DgroupId=com.w -DartifactId=javaweb-01-maven -Dversion=1.0-SNAPSHOT -DarchetypeArtifactId=maven-archetype-webapp -DarchetypeVersion=RELEASE -DinteractiveMode=false
|
idea中配置Tomcat
添加配置(Run/Debug Configuration)-> Add New Configuration -> Tomcat Server(Local)
name随便填,配置Application server为tomcat所在目录,配置JRE为jdk所在目录;在deployment中创建Artifact解决warning,Application context为虚拟目录,配置为xxx则访问路径为http://[ip]:8080/xxx/
配置完成后即可启动项目
pom.xml
以javaweb-01-maven项目的pom.xml为例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| <?xml version="1.0" encoding="UTF-8"?>
<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>
<!-- 配置的GAV --> <groupId>com.w</groupId> <artifactId>javaweb-01-maven</artifactId> <version>1.0-SNAPSHOT</version> <!-- package:项目的打包方式。jar:java应用,war:javaweb应用--> <packaging>war</packaging>
<name>javaweb-01-maven Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url>
<!-- 配置 --> <properties> <!-- 项目的默认构建编码 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- 编码版本 --> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties>
<!-- 依赖 --> <dependencies> <!-- 具体依赖的jar包配置文件,maven的高级之处在于会帮你导入这个jar包所依赖的其他jar包--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies>
<!-- 项目构建用的东西 --> <build> <finalName>javaweb-01-maven</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> <!-- 在build中需要配置resources,防止资源导出失败的问题 --> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build> </project>
|
Tomcat
java的web 容器
安装
1 2 3 4 5 6 7 8 9
| 解压到/opt下 sudo tar -zxvf apache-tomcat-9.0.62.tar.gz -C /opt
配置全局环境变量 sudo vim /etc/profile export CATALINA_HOME=/opt/apache-tomcat-9.0.62
使环境变量生效 source /etc/profile
|
Mybatis第一个程序
思路流程:搭建环境–>导入Mybatis—>编写代码—>测试
创建maven项目
1
| mvn archetype:generate -DgroupId=com.w -DartifactId=Mybatis-Study -Dversion=1.0-SNAPSHOT -DinteractiveMode=false
|
编写mybatis核心配置文件
用于设置mybatis数据库连接驱动,host,用户名和密码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <?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://192.168.1.50:33060/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml"/> </mappers> </configuration>
|
编写mybatis工具类
mybatisUtils.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| package com.w.utils;
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 java.io.IOException; import java.io.InputStream;
public class mybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static { try { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); }
}
|
创建实体类
pojo.User
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| package com.w.pojo;
public class User { private int id; private String name; private String pwd;
public User() {
} public User(int id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } }
|
编写Mapper接口类
dao.UserDao等同于UserMapper
1 2 3 4 5 6 7 8 9
| package com.w.dao;
import com.w.pojo.User;
import java.util.List;
public interface UserDao { List<User> getUserList(); }
|
编写Mapper.xml配置文件
dao.UserMapper.xml,使用了绑定的方式,实现了mapper接口类中的getUserList方法,注意namespace写UserMapper接口类的完全限定名,id写绑定的方法,以及resultType要写完全限定名
1 2 3 4 5 6 7 8 9 10 11 12
| <?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"> <!--namespace绑定一个Dao/Mapper接口--> <mapper namespace="com.w.dao.UserDao"> <!--select查询语句,id绑定抽象方法,resultType为返回的实体类--> <select id="getUserList" resultType="com.w.pojo.User"> select * from mybatis.user where id = #{id} </select>
</mapper>
|
测试
junit测试,test.java.com.w.dao.UserDaoTest
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class UserDaoTest {
@Test public void test() { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); List<User> userList = userDao.getUserList();
for (User user : userList) { System.out.println(user); }
sqlSession.close();
} }
|
可能会遇到的问题:
- 配置文件没有注册
- 绑定接口错误
- 方法名不对
- 返回类型不对
- Maven导出资源问题
小结
主要有七个步骤:
- 创建maven项目,配置pom.xml
- 编写mybatisUtils工具类,封装读取数据库配置文件并返回sqlSession
- 上一步需要一个数据库连接配置文件,故创建resources\mybatis-config.xml 数据库连接配置文件
- 建立pojo\user用户实体类
- UserDao抽象接口,也可以写作UserMapper
- UserMapper.xml配置sql方法,绑定了抽象接口的getUserList方法,等同于实现了这个方法
- 编写测试UserDaoTest,调用getUserList方法
CRUD操作及配置解析
select
步骤:
- UserMapper.java接口中添加接口
- UserMapper.xml配置文件中绑定selectUserById接口,即实现它。
- 在UserMapperTest.java中实现测试类
UserMapper.java
1
| User selectUserById(int id);
|
UserMapper.xml
1 2 3
| <select id="selectUserById" resultType="com.w.pojo.User" parameterType="int"> select * from mybatis.user where id = #{id} </select>
|
UserMapperTest.java
1 2 3 4 5 6 7 8
| @Test public void testSelectUserById() { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.selectUserById(1); System.out.println(user); sqlSession.close(); }
|
insert
UserMapper.java
UserMapper.xml
1 2 3
| <insert id="addUser" parameterType="com.w.pojo.User"> insert into mybatis.user (id, name, pwd) values (#{id}, #{name}, #{pwd}); </insert>
|
UserMapperTest.java
1 2 3 4 5 6 7 8 9
| @Test public void testAddUser() { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); userMapper.addUser(new User(4, "嘿嘿", "123qwe")); sqlSession.commit(); sqlSession.close(); }
|
update
UserMapper.java
1
| int updateUser(User user);
|
UserMapper.xml
1 2 3
| <update id="updateUser" parameterType="com.w.pojo.User"> update mybatis.user set name = #{name}, pwd = #{pwd} where id = #{id}; </update>
|
UserMapperTest.java
1 2 3 4 5 6 7 8 9
| @Test public void testUpdateUser() { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); userMapper.updateUser(new User(4, "哈哈", "123qwe")); sqlSession.commit(); sqlSession.close(); }
|
delete
UserMapper.java
UserMapper.xml
1 2 3
| <delete id="deleteUser" parameterType="int"> delete from mybatis.user where id = #{id}; </delete>
|
UserMapperTest.java
1 2 3 4 5 6 7 8 9
| @Test public void testDeleteUser() { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); userMapper.deleteUser(4); sqlSession.commit(); sqlSession.close(); }
|
注意点:增删改需要事务
万能map
在insert操作时,如果参数类型为一个User对象com.w.pojo.User, 那么需要在insert语句中将这个对象的每个属性都写出来,如果该对象有过多的属性,每个都写出来就非常不方便。所以参数类型可以传入一个map
insert
UserMapper.java
1
| int addUser2(Map<String, Object> map);
|
UserMapper.xml
1 2 3
| <insert id="addUser2" parameterType="map"> insert into mybatis.user (id, pwd) values (#{userid}, #{password}); </insert>
|
UserMapperTest.java
1 2 3 4 5 6 7 8 9 10 11 12
| @Test public void testAddUser2() { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); Map<String, Object> map = new HashMap<String, Object>(); map.put("userid", 5); map.put("password", "qweqwe"); userMapper.addUser2(map); sqlSession.commit(); sqlSession.close(); }
|
select
UserMapper.java
1
| User selectUserById2(Map<String, Object> map);
|
UserMapper.xml
1 2 3
| <select id="selectUserById2" resultType="com.w.pojo.User" parameterType="map"> select * from mybatis.user where id = #{userid} </select>
|
UserMapperTest.java
1 2 3 4 5 6 7 8 9 10 11
| @Test public void testSelectUserById2() { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); HashMap<String, Object> map = new HashMap<>(); map.put("userid", 2);
User user = userMapper.selectUserById2(map); System.out.println(user); sqlSession.close(); }
|
小结
Map传递参数,直接在sql中取出key即可
对象传递参数,直接在sql中取对象的属性即可
只有一个基本类型的情况下,可以直接在sql中取到
多个参数用Map,或者注解
模糊查询
注意sql注入的问题
java代码执行的时候传递通配符% %
1
| List<User> userList = userMapper.selectUsersLike("%张%");
|
在sql拼接中使用通配符% %
1
| select * from mybatis.user where name like "%"#{value}"%"
|
配置解析
- mybatis-config.xml 系统核心配置文件
- 能配置的内容如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| configuration(配置) properties(属性) settings(设置) typeAliases(类型别名) typeHandlers(类型处理器) objectFactory(对象工厂) plugins(插件) environments(环境配置) environment(环境变量) transactionManager(事务管理器) dataSource(数据源) databaseIdProvider(数据库厂商标识) mappers(映射器)
|
environment
数据库连接配置,能配置多套环境
mappers
定义映射SQL语句文件,告诉 MyBatis 到哪里去找到这些语句
Properties
数据库这些属性都是可外部配置且可动态替换的,配置与代码分离
db.properties
1 2 3 4
| driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://192.168.1.50:33060/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT username=root password=root
|
mybatis-config.xml
1
| <properties resource="db.properties"/>
|
typeAliases