ssm
Spring :业务层框架
SpringMVC :开发web应用的模块 model+view+controller
Mybatis :持久化 jdbcmysql
Mybatis
1、创建项目及模块
2、添加pom.xml
<?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>
<groupId>com.ly.mybatis</groupId>
<artifactId>mybatisdemo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
</project>
3、添加配置 [resources/mybatis-config.xml]
<?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/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
</configuration>
4、创建数据库和表
5、测试连接
public static void main(String[] args) {
try{
//配置文件路径(类路径)
String resource = "mybatis-config.xml";
//加载文件
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建会话工厂Builder,相当于连接池。
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//通过sqlSessionFactory开启会话,相当于打开连接。
SqlSession sqlSession = sqlSessionFactory.openSession();
System.out.println(sqlSession);
}catch(IOException e){
e.printStackTrace();
}
}
6、编写Mapper文件。
a)创建user类,和user表对应。
b)创建userMapper.xml文件,
[domain/UserMapper]
<?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="tUser">
<insert id = "insert" >
INSERT into tUser(name,age) values(#{name},#{age});
</insert>
</mapper>