标签:
Mybatis不管在什么工程中都可以使用,只要倒入所需要的jira,并进行简单的配置即可。
这里以对oracle数据库操作为例
1.倒入jira包:mybatis-3.1.1.jar和ojdbc6.jar。
2.建立实体类,用于映射数据表。
public class Person { private Integer id; private String name; private Integer age; //必须保证该类有个默认的构造器,不然在映射数据的时候将无法创建该类对象 public Person() { // TODO Auto-generated constructor stub } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
3.建立Dao接口映射,即创建一个操作数据表的接口,里面是操作数据表的方法声明,这面的方法名要和之后创建的mapper配置文件中的id对于
public interface PersonMapper { void insertPerson(Person person); }
4.建立mybatis主配置文件
<?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="lazyLoadingEnabled" value="false" /> </settings> <typeAliases> <typeAlias alias="person" type="com.lxw.domain.Person"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@localhost:1521:Sudy"/> <property name="username" value="JGCWDEV"/> <property name="password" value="11111111"/> </dataSource> </environment> </environments> <mappers>
<!--这里的路径一定要对--> <mapper resource="com/lxw/service/dao/PersonMapper.xml"/> </mappers> </configuration>
5.建立映射文件
<?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="com.lxw.service.dao.PersonMapper"> <!--表名--> <sql id=‘TABLE_NAME‘>person</sql>
<!--取序列的值--> <sql id=‘TABLE_SEQUENCE‘>person_seq.nextval</sql>
<!--sql语句后面不能有封号--> <insert id="insertPerson" parameterType="person"> insert into <include refid="TABLE_NAME" /> (id,name,age) values (<include refid="TABLE_SEQUENCE" />,#{name},#{age}) </insert> </mapper>
6.测试
public class TestMyBaties extends TestCase { //指定MyBatis配置文件 private static final String RESOURCE = "mybatis-config.xml"; public void testBaties() throws IOException{ //1、指定MyBatis配置文件 Reader reader = Resources.getResourceAsReader(RESOURCE); //2、创建SqlSessionFactory() SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = null; try { //3、获取SqlSession session = sessionFactory.openSession(); //4、获取DAO接口对象 PersonMapper mapper = session.getMapper(PersonMapper.class); Person person = new Person(); person.setName("demo"); person.setAge(11); mapper.insertPerson(person); session.commit();//添加、修改、删除操作最后需要提交事务 } catch (Exception e) { e.printStackTrace(); }finally{ //6、关闭SqlSession if(session != null){ session.close(); } } } }
标签:
原文地址:http://www.cnblogs.com/lvxiaowei/p/4230923.html