扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

MyBatis鍗曞厓娴嬭瘯鎬庝箞瀹炵幇

扬州沐宇科技
2024-03-08 09:28:30
mybatis

鍦∕yBatis涓繘琛屽崟鍏冩祴璇曠殑瀹炵幇鍙互閫氳繃浣跨敤MyBatis鎻愪緵鐨勫唴瀛樻暟鎹簱H2锛屾潵妯℃嫙鏁版嵁搴撶幆澧冭繘琛屾祴璇曘€備互涓嬫槸涓€涓畝鍗曠殑MyBatis鍗曞厓娴嬭瘯鐨勫疄鐜版楠わ細

  1. 娣诲姞H2渚濊禆锛氬湪pom.xml鏂囦欢涓坊鍔燞2鏁版嵁搴撶殑渚濊禆锛屽涓嬫墍绀猴細
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.200</version>
    <scope>test</scope>
</dependency>
  1. 缂栧啓娴嬭瘯绫伙細缂栧啓涓€涓户鎵胯嚜JUnit鐨勬祴璇曠被锛屽苟娣诲姞@Test娉ㄨВ鏍囪涓烘祴璇曟柟娉曪紝濡備笅鎵€绀猴細
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class MyBatisTest {

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Test
    public void testSelect() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            // 鑾峰彇Mapper鎺ュ彛
            MyMapper mapper = sqlSession.getMapper(MyMapper.class);
            // 璋冪敤Mapper鏂规硶
            MyEntity result = mapper.selectById(1);
            // 鏂█鍒ゆ柇缁撴灉
            assertNotNull(result);
            assertEquals("test", result.getName());
        } finally {
            sqlSession.close();
        }
    }

}
  1. 缂栧啓Mapper鎺ュ彛鍜孧apper.xml鏂囦欢锛氬垱寤轰竴涓狹apper鎺ュ彛鍜屽搴旂殑Mapper.xml鏂囦欢锛屽畾涔夋暟鎹簱鎿嶄綔鏂规硶鍜孲QL璇彞銆?/p>

  2. 缂栧啓MyBatis閰嶇疆鏂囦欢锛氱紪鍐橫yBatis閰嶇疆鏂囦欢锛岄厤缃暟鎹簮鍜孧apper鎺ュ彛鐨勬壂鎻忚矾寰勩€?/p>

  3. 杩愯娴嬭瘯锛氬湪娴嬭瘯绫讳腑鍙抽敭鐐瑰嚮鈥淩un As鈥?-> 鈥淛Unit Test鈥濇潵杩愯娴嬭瘯銆?/p>

閫氳繃浠ヤ笂姝ラ锛屽氨鍙互瀹炵幇涓€涓畝鍗曠殑MyBatis鍗曞厓娴嬭瘯銆傚湪瀹為檯椤圭洰涓紝杩樺彲浠ヤ娇鐢∕ockito绛夊伐鍏锋ā鎷熷璞★紝浠ュ強浣跨敤Spring Test鏉ヨ繘琛岄泦鎴愭祴璇曠瓑鏇村姞澶嶆潅鐨勬祴璇曞満鏅€?/p>

扫码添加客服微信