Mybatis学习之注解

 配置文件mybatis-config.xml,注意mapper映射的是接口,不是SQL映射文件

<?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>
	<!-- 命名别名 -->
	<typeAliases>
		<typeAlias alias="Person" type="com.mybatis.bean.Person" />
	</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/test" />
				<property name="username" value="root" />
				<property name="password" value="root" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper class="com.mybatis.inter.PersonDAO"/>
	</mappers>
</configuration>

  mapper接口,通过注解来定义SQL语句

package com.mybatis.inter;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.mybatis.bean.Person;

public interface PersonDAO {

	@Insert("insert into person(name,age) values(#{name},#{age})")
	public void add(Person person);

	@Delete("delete from person where id=#{id}")
	public void delete(int id);

	@Select("select * from person where id=#{id}")
	public Person queryById(int id);

	@Select("select * from person")
	public List<Person> findAll();

	@Update("update person set name=#{name},age=#{age} where id=#{id}")
	public void update(Person person);

}

  测试:

package com.mybatis.test;

import java.io.IOException;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.mybatis.bean.Person;
import com.mybatis.inter.PersonDAO;
import com.mybatis.util.MybatisUtil;

public class Test {

	public static void main(String[] args) {
		SqlSessionFactory factory=null;
		SqlSession session=null;
		try {
			factory=MybatisUtil.getSqlSessionFactory();
			session=factory.openSession();
			PersonDAO personDAO = session.getMapper(PersonDAO.class);
//			Person person=new Person();
//			person.setName("zcs");
//			person.setAge(25);
//			personDAO.add(person);
//			session.commit();
			List<Person> persons = personDAO.findAll();
			for(Person p:persons) {
				System.err.println(p.getName() +" " +p.getAge());
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
	}

}

  

posted @ 2015-09-29 09:38  zcs_dlut  阅读(177)  评论(0编辑  收藏  举报