您好,欢迎来到意榕旅游网。
搜索
您的当前位置:首页IDEA使用Spring、Mybatis实现简单的数据库查询。

IDEA使用Spring、Mybatis实现简单的数据库查询。

来源:意榕旅游网
IDEA使⽤Spring、Mybatis实现简单的数据库查询。

⼀、创建⼀个mavan项⽬

⼆、创建两个module,dao层和entity层

三、在根层添加spring-context,spring-core,spring-beans,spring-jdbc,mybatis,mysql等dao层依赖

org.springframework spring-beans 5.0.8.RELEASE

org.springframework spring-context 5.0.8.RELEASE

org.springframework spring-core 5.0.8.RELEASE

com.mchange c3p0 0.9.5.2

org.mybatis

mybatis-spring 1.3.2

org.springframework spring-jdbc 5.0.9.RELEASE

mysql

mysql-connector-java 8.0.12

org.mybatis mybatis 3.4.6

四、在dao层创建⼀个StudentMapper接⼝

五、在接⼝内添加⼀个findAllStudent查询学⽣⽅法

六、在dao层resources⽬录创建⼀个mapper⽬录⽤于存放Mapper.xml映射⽂件

 

Mapper.xml中所需要的映射信息及sql查询语句,需要注意的是因为没有mybatis-config.xml配置⽂件的配合,resultMap映射集的类型需要加上包名

七、在resources⽬录下创建applicationContext.xml Spring容器配置⽂件

applicationContext代码如下:myDataSource连接池中记录着连接信息,

xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd\">

     //引⽤了myDataSource连接池

     //在mapper⽬录下找到Mapper.xml映射⽂件

⼋、在entity层创建Student实体类,并使⽤快捷⽅式写出get()set()⽅法

九、在dao层再创建⼀个test包写⼀个Test类,在Test类中写main()⽅法开始测试

测试代码如下:

package com.nf.test;

import com.nf.mapper.StudentMapper;

import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test {

public static void main(String args[]){

     //实例化⼀个ClassPathXmlApplicationContext通过⽂件名查找⽅式找到

ApplicationContext ac = new ClassPathXmlApplicationContext(\"applicationContext.xml\");     //通过getBean⽅法找到applicationContext中的mySqlSessionFactory

SqlSessionFactory factory = (SqlSessionFactory) ac.getBean(\"mySqlSessionFactory\"); SqlSession sqlSession = factory.openSession();

StudentMapper studao = sqlSession.getMapper(StudentMapper.class);     //通过findAllStudent()⽅法查询数据库打印出数据的长度 System.out.println(studao.findAllStudent().size());

}}

⼗、测试结果成功,为七条

数据库中的数据为七条,验证成功

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- yrrf.cn 版权所有 赣ICP备2024042794号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务