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"/> <! - configuration data source Four connection properties need to configure the database --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <-! Database url -> <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!-- mappers tag to configure the profile to sql mapper --> <mappers> <-! Mapper introduced a configuration file sql statement resource properties you want to configure the profile path introduced --> <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 is to use variable (and the corresponding fields in the database)
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 name space (usually there are two values) A: javaBean corresponding full class name II: Full class name corresponding interface Mapper --> <mapper namespace="com.pojo.User"> <!-- select tag indicates the select statement id is currently the sql statement to configure a unique identifier After resultType select query is executed, each row corresponding to record the full class name of the object javaBean # {id} in mybatis bit symbol midpoint ? --> <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(); } }