Mybatis的开发流程
本文最后更新于:3 天前
Mybatis的开发流程
1、引入依赖,Mybatis依赖和对应数据库的连接驱动
1 2 3 4 5 6 7 8 9 10
| <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency>
|
2、在Mybatis配置文件中配置数据路连接信息
- Mybatis配置文件 mybatis-config.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
| <?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> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <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/数据库名" /> <property name="username" value="root" /> <property name="password" value="password" /> </dataSource> </environment> </environments> <mappers>
</mappers> </configuration>
|
3、创建于数据表字段一致的实体类
1 2 3 4 5 6 7 8 9 10 11
| public class Employee { private Integer empno; private String ename; private String job; private Integer mgr; private Date hiredate; private Float sal; private Float comm; private Integer deptno; }
|
4、创建用于书写SQL语句的xml文件
1 2 3 4 5 6 7 8
| <?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="..mapper.EmpMapper"> <select id="findById" parameterType="int" resultType="..entity.Employee"> select * from emp where empno = #{value} </select> </mapper>
|
1 2 3 4 5
| <configuration> <mappers> <mapper resource="mapper/emp.xml"></mapper> </mappers> </configuration>
|
5、启动程序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public static void main(String[] args) { String resource = "mybatis-config.xml"; Reader reader = Resources.getResourceAsReader(resource); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); String statement = "..mapper.EmpMapper.findById"; SqlSession session = sessionFactory.openSession(); Employee emp = session.selectOne(statement, 7566); System.out.println(emp.getName()); session.close(); }
|