问题:
MyBatis demo
解决:
完整代码:https://github.com/giant35/mybatis1
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
final InputStream is = App.class.getClassLoader().getResourceAsStream("mybatis.xml"); Objects.requireNonNull(is); SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(is); SqlSession s = sf.openSession(); System.out.println("after open session"); int id ; { T1 t = new T1(); t.setName("tom1"); s.insert("mybatis1.T1Mapper.insertT1", t); s.commit(); System.out.println("after insert commit"); id = t.getId(); } { T1 t2 = s.selectOne("mybatis1.T1Mapper.selectT1", id); System.out.println(t2); } s.close(); |
mybatis.xml:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?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://localhost:3306/test2"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mybatis1/T1Mapper.xml"/> </mappers> </configuration> |
mybatis1/T1Mapper.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?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="mybatis1.T1Mapper"> <select id="selectT1" resultType="mybatis1.T1"> select * from t1 where id = #{id} </select> <insert id="insertT1" useGeneratedKeys="true" keyProperty="id" > insert into t1 (name) value (#{name}) </insert> </mapper> |
参考:
http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html