Mybatis


what is Mybatis

  • persistence framework with support for custom SQL
      


 A persistence framework assists and automates the storage of program data into databases, especially relational databases. It acts as a layer of abstraction between the application and the database, typically bridging any conceptual differences between the two.

Dao

  • Java Data Access Object

  • All database access in the system is made through a DAO to achieve encapsulation.
  • Each DAO instance is responsible for one primary domain object or entity. If a domain object has an independent lifecycle, it should have its own DAO.
  • The DAO is responsible for creations, reads (by primary key), updates, and deletions -- that is, CRUD --

  • The DAO is not responsible for handling transactions, sessions, or connections. These are handled outside the DAO to achieve flexibility.

DAo


@Repository
public interface EmployeeDao {
	public void saveEmployee(Employee employee);

	public Employee getEmployeeById(Integer employeeId);
}

XMl Mapper

 <?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="ro.cf.mybatisTutorial.EmployeeDao">

	<insert id="saveEmployee" useGeneratedKeys="true" keyProperty="id">
		INSERT INTO employees (emp_no, birth_date, first_name, last_name,
		gender, hire_date)
		VALUES ( #{emp_no}, #{birth_date}, #{first_name}, #{last_name}, #{gender},
		#{hire_date} );
	</insert>

        <select id="getEmployeeById" resultType="ro.cf.mybatisTutorial.Employee">
		SELECT * from employees WHERE emp_no = #{employeeId};
	</select>

</mapper>

USing dao

  • using the @AutoWired adnotation

 
  @Autowired
  private EmployeeDao employeeDao;

...
  Employee employee = employeeDao.getEmployeeById(1);

Made with Slides.com