在resource包下面的两个配置文件
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:///student?useSSL=false"/> <property name="username" value="root"/> <property name="password" value="a1b2c3"/> </dataSource> </environment> </environments> <mappers> <mapper resource="usermapper.xml"/> </mappers> </configuration> usermapper.xml:
<!-- 写sql语句的 --> <?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="selectAll" resultType="it.student"> select * from student; </select> </mapper> test:
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; import java.util.List; public class test { public static void main(String[] args) throws IOException { //加载mybatis核心配置文件,获取sqlSession String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //获取对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //执行sql List<Object> objects = sqlSession.selectList("test.selectAll"); System.out.println(objects); sqlSession.close(); } }