标签:dtd jdbc 文件夹 tab driver 注意 exce put localhost
一.整体步骤
1.读取全局配置文件“SqlMapConfig.xml”
2.用SqlSessionFactoryBuilder来创建一个SqlSessionFactory
3.用创建好的SqlSessionFactory创建一个SqlSession
4.用创建好的SqlSession来读取对应的映射配置文件“Mapper1.xml”,并传入参数
5.返回结果
--------------------------------------------------------------------------------------------------------------------------------------------
二.具体步骤
1.新建maven项目
eclipse菜单找到“File”->"new"->"Project",选择Maven Project
2.在配置文件pom.xml下的denpencies添加denpency
mybatis的jar包和mysql的jdbc驱动
<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.35</version> </dependency>
3.在src/main下新建资源文件夹"resources",并添加SqlMapConfig.xml、具体映射配置文件Mapper.xml和数据库参数文件db.properties
SqlMapConfig.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> <properties resource="db.properties"></properties> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="StudentMapper.xml"/> </mappers> </configuration>
db.properties的源码:
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8 username=root password=123456
Mapper.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"> <select id="selectPerson" parameterType="int" resultType="com.mavenTest.mybatis_test.Person"> select * from Persons_table where id = #{id} </select> </mapper>
4.在main/java下的任意jar包中创建一个pojo,这里例如是Person.class(注意对应好上面的resultType的路径)
public class Person{ private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
5.在java/main的任意jar包创建一个任意类
public class pratise { public static void main(String[] args) throws IOException{ InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(is); SqlSession ss = ssf.openSession(); Student s = ss.selectOne("selectStudent", 827); System.out.println(s.getName()); } }
这样就已经可以实现数据库语句的调用了
标签:dtd jdbc 文件夹 tab driver 注意 exce put localhost
原文地址:https://www.cnblogs.com/amiezhang/p/9574214.html