mybatis 기본 정보


머리말

mybatis의 기본 정보를 기억하십시오.


1. Mybatis 전통 및 에이전트 개발

UserDao 인터페이스 작성

public interface UserDao {
    
    
	List<User> findAll() throws IOException;
} 

UserDaoImpl 구현 작성

public class UserDaoImpl implements UserDao {
    
    
	public List<User> findAll() throws IOException {
    
    
	InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
	SqlSession sqlSession = sqlSessionFactory.openSession();
	List<User> userList = sqlSession.selectList("userMapper.findAll");
	sqlSession.close();
	return userList;
	}
}

전통적인 방식 테스트

@Test
public void testTraditionDao() throws IOException {
    
    
	UserDao userDao = new UserDaoImpl();
	List<User> all = userDao.findAll();
	System.out.println(all); 
}

에이전트 개발 방법 :
mybatis 프레임 워크는 인터페이스 m의 정의에 따라 인터페이스의 동적 에이전트 객체를 생성하며 에이전트 객체의 메서드 본문은 위의 Dao 인터페이스 구현 클래스 메서드와 동일합니다.
매퍼 인터페이스 개발은 다음 사양을 따라야합니다.
1. Mapper.xml 파일의 네임 스페이스는 매퍼 인터페이스의 정규화 된 이름과 동일합니다. 2.
매퍼 인터페이스 메서드 이름은에 정의 된 각 문의 ID와 동일합니다.
Mapper.xml 3. Mapper 인터페이스 메소드의 입력 매개 변수 유형은
mapper.xml에 정의 된 각 SQL의 parameterType과 동일합니다 . 4. Mapper 인터페이스 메소드의 출력 매개 변수 유형은 정의 된 각 SQL의 resultType과 동일합니다. mapper.xml
여기에 사진 설명 삽입
테스트 프록시 모드에서

@Test
public void testProxyDao() throws IOException {
    
    
	InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
	SqlSession sqlSession = sqlSessionFactory.openSession();
	//获得MyBatis框架⽣成的UserMapper接⼝的实现类
	UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
	User user = userMapper.findById(1);
	System.out.println(user);
	sqlSession.close();
}

둘째, Mybatis 구성 파일

1. 핵심 구성 파일 SqlMapConfig.xml

여기에 사진 설명 삽입

1.1 일반적인 구성 분석

1.1.1 환경 레이블 (데이터베이스 환경 구성, 다중 환경 구성 지원)

여기에 사진 설명 삽입
그중
두 가지 유형의 트랜잭션 관리자 (transactionManager)가 있습니다.

  • JDBC :이 구성은 트랜잭션
    도메인 을 관리하기 위해 데이터 소스에서 얻은 연결에 의존하는 JDBC의 커밋 및 롤백 설정을 직접 사용 합니다.
  • 관리 :이 구성은 거의 아무것도하지 않습니다. 연결을 커밋하거나 롤백하지 않지만 컨테이너
    트랜잭션의 전체 수명주기 (예 : JEE 응용 프로그램 서버의 컨텍스트)를 관리하도록합니다. 기본적으로 연결을 닫지 만 일부 컨테이너에서는이를 원하지
    않으므로 closeConnection 속성을 false로 설정하여 기본 동작을 닫지 않도록해야합니다.

dataSource에는 세 가지 유형이 있습니다.

  • UNPOOLED :이 데이터 소스의 구현은 요청 될 때마다 연결을 열고 닫습니다.
  • POOLED :이 데이터 소스의 실현은 "pool"개념을 사용하여 JDBC 연결 개체를 구성합니다.
  • JNDI :이 데이터 소스는 EJB 또는 애플리케이션 서버와 같은 컨테이너에서 사용되도록 구현됩니다. 컨테이너는
    데이터 소스를 중앙 또는 외부 에서 구성한 다음 JNDI 컨텍스트에 대한 참조를 배치 할 수 있습니다.

1.1.2 매퍼 태그 (지도를로드하는 역할)

로딩 방법 :

•使用相对于类路径的资源引用,例如:
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
•使用完全限定资源定位符(URL),例如:
<mapper url="file:///var/mappers/AuthorMapper.xml"/>
•使用映射器接口实现类的完全限定类名,例如:
<mapper class="org.mybatis.builder.AuthorMapper"/>
•将包内的映射器接口实现全部注册为映射器,例如:
<package name="org.mybatis.builder"/>

1.1.3 속성 탭

실제 개발에서는 데이터 소스의 구성 정보를 속성 파일로 별도로 추출하는 것이 일반적이며이 태그는 추가 구성 속성 파일을로드 할 수 있습니다.
여기에 사진 설명 삽입

1.1.4 typeAliases 태그 (별칭 유형, Java 유형에 대한 짧은 이름 설정)

! [] (https://img-blog.csdnimg.cn/20210112183132344.png
mybatis 프레임 워크는 이미 일반적으로 사용되는 별칭 유형을 설정했습니다.

별명 매핑 유형
_바이트 바이트
_긴
_짧은 짧은
_int int
_정수 int
_더블 더블
_흙손 흙손
_boolean 부울
바이트 바이트
짧은 짧은
int 정수
정수 정수
더블 더블
흙손 흙손
부울 부울
데이트 데이트
소수 BigDecimal
bigdecimal BigDecimal
목적 목적
지도 지도
해시 맵 HashMap
명부 명부
배열 목록 ArrayList
수집 수집
반복자 반복자

2. 매핑 구성 파일 mapper.xml

판단하면

<select id="findByCondition" parameterType="user" resultType="user">
	select * from User
	<where>
		<if test="id!=0">
			and id=#{
    
    id}
		</if>
		<if test="username!=null">
			and username=#{
    
    username}
		</if>
	</where>
</select>

루프 SQL 연결

<select id="findByIds" parameterType="list" resultType="user">
	select * from User
	<where>
		<foreach collection="list" open="id in(" close=")" item="id" separator=",">
			#{
    
    id}
		</foreach>
	</where>
</select>

foreach 태그는 컬렉션을 순회하는 데 사용됩니다.

  • collection : 순회 할 컬렉션 요소를 나타냅니다. 작성시 # {}을 쓰지 않도록주의하십시오.
  • open : 문의 시작을 나타냅니다.
  • 닫기 : 끝 부분을 나타냅니다.
  • item : 순회 컬렉션의 각 요소, 생성 된 변수 이름을 나타냅니다.
  • sperator : 구분자를 나타냅니다.

SQL 조각 추출
Sql은 중복 SQL을 추출하고 사용할 때 포함을 사용하여 인용하고 마지막으로 SQL 재사용 목적을 달성 할 수 있습니다.

<!--抽取sql片段简化编写-->
<sql id="selectUser" select * from User</sql>
<select id="findById" parameterType="int" resultType="user">
	<include refid="selectUser"></include> where id=#{
    
    id}
</select>
<select id="findByIds" parameterType="list" resultType="user">
	<include refid="selectUser"></include>
	<where>
		<foreach collection="array" open="id in(" close=")" item="id" separator=",">
			#{
    
    id}
		</foreach>
	</where>
</select>

추천

출처blog.csdn.net/weixin_39417423/article/details/112541360