MyBatis基本使用1
1.pom.xm中添加依赖坐标
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.5</version> </dependency>
2.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="mysql"> <!--配置Mysql的环境--> <environment id="mysql"> <!--配置事务的类型--> <transactionManager type="JDBC"></transactionManager> <!--配置数据源(连接池)--> <dataSource type="POOLED"> <!--配置连接数据库的四个基本信息--> <property name="driver" value="org.postgresql.Driver" /> <property name="url" value="jdbc:postgresql://localhost:5432/wh3" /> <property name="username" value="postgres" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <mappers> <!--加载sql的映射文件--> <mapper resource="TestMapper.xml" /> </mappers> </configuration>
3.TestMapper.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="GetAll" resultType="com.ld.model.Test" > select * from test; </select> </mapper>
4.使用
//加载mybatis配置文件,SqlSessionFactory String resource="mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //获取sqlsession对象,用来执行sql SqlSession sqlSession=sqlSessionFactory.openSession(); //执行sql List<Test> tests= sqlSession.selectList("test.GetAll"); System.out.println(tests); sqlSession.close();