javamagicsun 2020-01-29
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"/> <!--数据库url --> <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!-- mappers标签用来配置 sql 的 mapper配置文件 --> <mappers> <!-- mapper引入一个sql语句的配置文件 resource属性配置你要引入的配置文件的路径 --> <mapper resource="com/pojo/UserMapper.xml"/> </mappers> </configuration>
log4j.properties
# Global logging configuration log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
User.java中的成用变量(同时对应数据库中的字段)
private Integer id; private String lastName; private Integer sex;
UserMapper.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"> <!-- namespace 名称空间(一般有两种值) 一:对应的javaBean的全类名 二:对应的Mapper接口的全类名 --> <mapper namespace="com.pojo.User"> <!-- select 标签表示select语句 id 是给当前这个sql语句配置一个唯一标识 resultType 执行了select查询语句之后,每行记录对应的javaBean对象全类名 #{id} 在mybatis中点位符 ? --> <select id="selectUserById" resultType="com.pojo.User"> select id,last_name lastName,sex from t_user where id = #{id} </select> </mapper>
test
@Test public void test2() throws Exception { InputStream is=Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(is); //获取session对象 SqlSession ss=sqlSessionFactory.openSession(); System.out.println(2); try { User user = ss.selectOne("com.pojo.User.selectUserById", 1); System.out.println(user); } finally { // TODO: handle finally clause ss.close(); } }