MyBatis3.1.1简单示例
这是一个普通Java Project,用的MyBatis3.1.1包。
1.引入mybatis-3.1.1.jar
2.编写实体类(XxBean.java),一定要有无参构造方法。
3.编写操纵实体类的接口(XxMapper.java),然后写一个对应的XML(XxMapper.xml)。
接口中的方法和XML中的ID对应,eg:
XxMapper.java:
public interface XxMapper{public void saveDataOnNotExist(XxBean);}
<?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="XxMapper"><insert id="saveDataOnNotExist" parameterType="XxBean"> insert into xx_bean(id) values (#{id})</insert> </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> <settings> <setting name="defaultExecutorType" value="REUSE" /> </settings> <typeAliases> <typeAlias alias=" XxBean" type="XxBean"/> </typeAliases> <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://127.0.0.1:3306/grap_data?characterEncoding=utf-8"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="XxMapper.xml" /> </mappers> </configuration>
package page; import java.io.IOException; import java.io.Reader; 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 MyBatisUtil { private static final String CONFIG_FILE_PATH = "mybatis-config.xml"; private static SqlSessionFactory sqlSessionFactory = null; private static SqlSession sqlSession = null; static{Reader reader = null;try{reader = Resources.getResourceAsReader(CONFIG_FILE_PATH); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);sqlSession = sqlSessionFactory.openSession();}catch(IOException e){e.printStackTrace();}finally{if(reader != null){try {reader.close();} catch (IOException e) {e.printStackTrace();}}} } public static SqlSession getSession(){return sqlSession; } }
package page; import XxMapper; import org.apache.ibatis.session.SqlSession; public class Test{ public static void main(String[] args) throws Exception{SqlSession sqlSession = MyBatisUtil.getSession();XxMapper xm= sqlSession.getMapper(XxMapper.class); xm.setId(1);dbm.saveDataOnNotExist(xm);sqlSession.commit(); } }