MyBatis5에서 Spring 통합 MyBatis 사물 관리

개별적으로 MyBatis를 사용하여 사물 관리
앞에서 MyBatis의 글은 관련 내용을 쓴 적이 있습니다. 여기서 가장 간단한 데모를 계속 씁니다. 이전의 MyBatis의 내용을 복습하는 셈입니다. 먼저 표를 작성하고 간단한 Student표를 만듭니다.

create table student
(
student_id int auto_increment,
student_name varchar(20) not null,
primary key(student_id)
)
실체 클래스 Student 만들기.java:

public class Student
{
private int studentId;
private String studentName;
public int getStudentId()
{
return studentId;
}
public void setStudentId(int studentId)
{
this.studentId = studentId;
}
public String getStudentName()
{
return studentName;
}
public void setStudentName(String studentName)
{
this.studentName = studentName;
}
public String toString()
{
return "Student{[studentId:" + studentId + "], [studentName:" + studentName + "]}";
}
} 
한마디만 더 하면 실체 클래스에 toString () 방법을 다시 쓰고 그 중 하나를 인쇄하는 것이 추천합니다.다음은 config.xml, jdbc 기본 설정:

<?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="Student" type="org.xrq.domain.Student" />
</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://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="student_mapper.xml"/>
</mappers>
</configuration> 
그리고 student _mapper.xml, 주로 구체적인 sql 문장:

<mapper namespace="StudentMapper">
<resultMap type="Student" id="StudentMap">
<id column="student_id" property="studentId" jdbcType="INTEGER" />
<result column="student_name" property="studentName" jdbcType="VARCHAR" />
</resultMap>
<select id="selectAllStudents" resultMap="StudentMap">
select student_id, student_name from student;
</select>
<insert id="insertStudent" useGeneratedKeys="true" keyProperty="studentId" parameterType="Student">
insert into student(student_id, student_name) values(#{studentId, jdbcType=INTEGER}, #{studentName, jdbcType=VARCHAR});
</insert>
</mapper> 
MyBatis Util을 만듭니다.java, MyBatis 기본 요소를 구축하는 데 사용되며, 뒤에 있는 클래스는 모두 이 클래스를 계승합니다.

public class MyBatisUtil
{
protected static SqlSessionFactory ssf;
protected static Reader reader;
static
{
try
{
reader = Resources.getResourceAsReader("config.xml");
ssf = new SqlSessionFactoryBuilder().build(reader);
} 
catch (IOException e)
{
e.printStackTrace();
}
}
protected SqlSession getSqlSession()
{
return ssf.openSession();
}
} 
엔터프라이즈급 개발 요구 사항:
1. 정의와 실현의 분리
2. 일반적으로 Dao-->Service-->Controller를 위한 계층형 개발
그래서 Student Dao를 먼저 쓰세요.java 인터페이스:

public interface StudentDao
{
public List<Student> selectAllStudents();
public int insertStudent(Student student);
}
마지막으로 Student DaoImpl을 쓰겠습니다.java는 이 인터페이스를 실현하고 MyBatis Util을 계승해야 합니다.java 클래스:

public class StudentDaoImpl extends MyBatisUtil implements StudentDao
{
private static final String NAMESPACE = "StudentMapper.";
public List<Student> selectAllStudents()
{
SqlSession ss = getSqlSession();
List<Student> list = ss.selectList(NAMESPACE + "selectAllStudents");
ss.close();
return list;
}
public int insertStudent(Student student)
{
SqlSession ss = getSqlSession();
int i = ss.insert(NAMESPACE + "insertStudent", student);
// ss.commit();
ss.close();
return i;
}
}
테스트 클래스 쓰기:

public class StudentTest
{
public static void main(String[] args)
{
StudentDao studentDao = new StudentDaoImpl();
Student student = new Student();
student.setStudentName("Jack");
studentDao.insertStudent(student);
System.out.println(" :" + student.getStudentId());
System.out.println("-----Display students------");
List<Student> studentList = studentDao.selectAllStudents();
for (int i = 0, length = studentList.size(); i < length; i++)
System.out.println(studentList.get(i));
}
}
결과는 틀림없이 비어 있을 것이다.
내가 말한 이 예는 복습이자 하나의 인용자로서 우리의 오늘의 내용을 도입한 것이다. 비어 있는 이유는 insert 조작이 이미 이루어졌기 때문이다. 그러나 MyBatis는 우리가 자동으로 사물을 제출하는 것을 도와주지 않기 때문에 보여주는 자연은 비어 있다.이럴 때는 SqlSession의commit() 방법을 통해 수동으로 업무를 제출해야 합니다. 즉, StudentDaoImpl을 열어야 합니다.자바 클래스 17줄의 주석만 있으면 됩니다.
한마디 더 말하자면 이 예는 기본적인 MyBatis 삽입 작업 외에 삽입을 바탕으로 삽입된 키 id를 되돌려주는 기능도 있다.
다음은 Spring을 이용하여 MyBatis 사물을 관리하는 것도 기업급 개발에서 가장 자주 사용하는 사물 관리 방법이다.
Spring을 사용하여 MyBatis 사물 관리
이것에 대해 인터넷에서 많은 설명이 있습니다. 제가 많이 검색했지만 서로 복사해서 붙이거나 전체 예를 명확하게 설명하지 않았습니다. 이 부분을 통해 저는 Spring을 사용하여 MyBatis 사물을 관리하는 방법을 최대한 명확하게 설명했습니다.
Spring을 사용하여 MyBatis 사물을 관리하려면 Spring에 필요한 모듈 beans,context,core,expression,commons-logging 외에 다음과 같은 내용이 필요합니다.
(1)MyBatis-Spring-1.x.0.jar, 이건 Spring 통합 MyBatis에 필요한 jar 패키지입니다.
(2) 데이터베이스 연결 탱크,dbcp,c3p0 모두 사용할 수 있습니다. 저는 아리의druid를 사용합니다.
(3) jdbc, tx, aop, jdbc는 기본적으로 많지 않다. tx와 aop을 사용하는 것은 스프링이 MyBatis 사물 관리에 대한 지원은 aop을 통해 이루어지기 때문이다.
(4)aopalliance.jar, 이것은 Spring AOP를 사용하기 위해 필요한 jar 패키지입니다.
위의jar 패키지는 Maven을 사용할 수 있습니다. Maven을 사용하지 않은 것은 CSDN에서 다운로드할 수 있습니다. 검색하면 됩니다.
MyBatis 구성 파일 config.xml에서 jdbc 연결에 대한 부분은 모두 제거하고 typeAliases의 부분만 보존합니다.

<?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="Student" type="org.xrq.domain.Student" />
</typeAliases>
</configuration> 
한마디만 더 하자면, MyBatis의 다른 프로필 student_mapper.xml은 변경할 필요가 없습니다.이어서 Spring의 프로필을 씁니다. 제 이름은spring입니다.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd 
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd 
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<!--   -->
<tx:annotation-driven transaction-manager="transactionManager" />
<context:annotation-config /> 
<context:component-scan base-package="org.xrq" />
<!--  , alibaba Druid -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="jdbc:mysql://localhost:3306/test" /> 
<property name="username" value="root" /> 
<property name="password" value="root" /> 
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:config.xml" />
<property name="mapperLocations" value="classpath:*_mapper.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
<!--   --> 
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
<property name="dataSource" ref="dataSource" /> 
</bean> 
</beans> 
이 안에는 주로 사무 관리자와 데이터베이스 연결 탱크 두 부분의 내용이 있다.
또한 우리는 Sql Session Factory가 있는 것을 보았다. My Batis를 사용한 친구들은 이 종류에 대해 낯설지 않을 것이다. 이것은 My Batis 환경을 설정하는 데 사용된다. Sql Session Factory에는 두 개의 속성인config Location,mapper Locations가 있다. 말 그대로 프로필의 위치와 맵 파일의 위치를 대표한다. 여기는 경로 설정이 정확하기만 하면 Spring은 자동으로 이 두 프로필을 불러온다.
그리고 수정할 것은 Dao의 실현 클래스입니다. 이때 이전의 MyBatis Util 클래스를 계승하지 않고 MyBatis-Spring-1을 계승합니다.x.0.jar 자체 SqlSessionDaoSupport.java, 구체적인 코드는 다음과 같습니다.

@Repository
public class StudentDaoImpl extends SqlSessionDaoSupport implements StudentDao
{
private static final String NAMESPACE = "StudentMapper.";
@Resource
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory)
{
super.setSqlSessionFactory(sqlSessionFactory);
}
public List<Student> selectAllStudents()
{
return getSqlSession().selectList(NAMESPACE + "selectAllStudents");
}
public int insertStudent(Student student)
{
return getSqlSession().insert(NAMESPACE + "insertStudent", student);
}
} 
여기에 두 개의 주석을 써서 각각 말해 보세요.
(1) @Repository, 이 메모와 @Component, @Controller, 그리고 우리가 가장 흔히 볼 수 있는 @Service 메모는 하나의 클래스를 Spring의 Bean으로 성명할 수 있는 작용을 한다.그것들의 차이는 구체적인 의미가 아니라 주해의 포지셔닝에 있다.앞서 말했듯이 기업급 응용은 층별 개발의 개념을 중시하기 때문에 이 네 가지 비슷한 주석에 대해 다음과 같은 이해를 가져야 한다.
• @Repository 메모, 대응하는 것은 지구층 즉 Dao층, 그 역할은 데이터베이스와 직접적으로 상호작용하는 것이다. 일반적으로 하나의 방법은 구체적인 Sql 문장에 대응하는 것이다
• @Service 주해, 대응하는 것은 서비스 계층 즉 서비스 층이다. 그 역할은 단일/여러 개의 Sql 문장을 조합 처리하는 것이다. 물론 간단하면 Dao층의 어떤 방법을 직접 호출한다.
• @Controller 메모는 컨트롤 레이어 즉 MVC 디자인 모델의 컨트롤 레이어로 사용자의 요청을 수신하고 요청에 따라 서로 다른 Service를 호출하여 데이터를 조합하고 포장하여 전방으로 되돌려주는 역할을 합니다.
• @Component 메모, 이것은 하나의 구성 요소에 대한 개념입니다. 만약에 Bean이 하나의 레이어에 속하는 것을 모른다면 @Component 메모를 사용하여 표시할 수 있습니다
이것 또한 주해의 장점 중 하나를 나타낸다. 명지의 뜻을 보면 이 주해를 보면 이런 종류의 작용, 즉 전체 프로젝트에서의 포지셔닝을 대체적으로 알 수 있다.
(2) @Resource, 이 메모와 @Autowired 메모는 속성 속성을 자동으로 주입할 수 있다는 뜻입니다.SqlSessionFactory는 MyBatis의 핵심이기 때문에spring에 있습니다.xml에서 성명이 진행되었기 때문에 @Resource 주석을 통해 id를'sqlSessionFactory'로 하는 Bean을 주입한 후 getSqlSession() 방법으로 SqlSession을 얻고 데이터의 증가, 삭제, 수정, 조회를 할 수 있습니다.
마지막으로 테스트 클래스를 써서 테스트를 하는 것이 틀림없다.

public class StudentTest
{
public static void main(String[] args)
{
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
StudentDao studentDao = (StudentDao)ac.getBean("studentDaoImpl");
Student student = new Student();
student.setStudentName("Lucy");
int j = studentDao.insertStudent(student);
System.out.println("j = " + j + "
"); System.out.println("-----Display students------"); List<Student> studentList = studentDao.selectAllStudents(); for (int i = 0, length = studentList.size(); i < length; i++) System.out.println(studentList.get(i)); } }
StudentDaoImpl 때문입니다.java 클래스는 @Repository 메모를 사용하고 별명을 지정하지 않았기 때문에 StudentDaoImpl.자바의 스프링 용기 이름은'이니셜 소문자 + 나머지 알파벳'즉'studentDaoImpl'입니다.
프로그램을 실행하면 컨트롤러에 new에서 나온 Student가 널리 퍼져 있는 것을 볼 수 있습니다. 즉, 이 Student는 데이터베이스에 직접 삽입되어 있습니다. 전체 과정에서 어떤commit,rollback도 없고 모두 Spring이 도와서 이루어진 것입니다. 이것이 바로 Spring을 이용하여 MyBatis에 대한 사물 관리를 하는 것입니다.
후기
본고는 MyBatis의 기본적인 사용과 Spring을 사용하여 MyBatis에 대한 사물 관리를 복습하고 비교적 상세한 코드 예를 제시하며 필요한 분들은 코드에 따라 연구할 수 있습니다.본고를 토대로 다음에 한 편의 글을 써서 다중 데이터가 단표와 다표 간의 사물 관리 실현에 대해 설명한다. 이런 수요도 기업과 응용에서 비교적 흔히 볼 수 있는 수요에 속한다.

좋은 웹페이지 즐겨찾기