mybatis mapper配置
<?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="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <!-- class 级别的指定 -->
<mapper class="cn.x.dao.Reg"/> <!-- xml 级别的指定 --> <mapper resource="org/mybatis/example/BlogMapper.xml"/> </mappers> </configuration>
dao类中多个参数需要在前面加注解@Param
执行insert之后需要session.commit()
import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class AA { String resource; InputStream inputStream; SqlSessionFactory sqlSessionFactory; public AA() throws Exception { resource = "mybatis-config.xml"; inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } public static void main(String[] args) throws Throwable { AA test1 = new AA(); SqlSession session = test1.sqlSessionFactory.openSession(); try { RegUtil regUtil = session.getMapper(RegUtil.class); System.out.println( regUtil.insertUser("1815277", "joy")); session.commit(); } finally { session.close(); } } }
import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Update; public interface RegUtil { @Insert("insert into t_test(id,name) values(${id},${name})" ) public boolean inserUser(@Param("id")Stringid,@Param("name")String name); }