使用的spring和Mybatis都是3.0.6直接上代码
JAVA代码:
ApplicationContext ac = new ClassPathXmlApplicationContext("springContext.xml");
SqlSession sqlSession = (SqlSession) ac.getBean("sqlSession");
//调用存储过程
Person person =(Person) sqlSession.selectOne("DataOperation.selectPro", Integer.valueOf(10));
//Person person =(Person) sqlSession.selectOne("DataOperation.selectInfo", Integer.valueOf(10));
System.out.println(person.getName());
数据库需要创建selectPerson存储过程(mysql)
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`selectPerson` $$
CREATE PROCEDURE `test`.`selectPerson` (`_age` int)
BEGIN
select * from people where age=_age;
END $$
DELIMITER ;
在工程下建立config文件夹,文件夹建立两个xml。一个mapper.xml 一个springContext.xml
springContext.xml内容:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="mapper.xml"></property>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory"></constructor-arg>
</bean>
</beans>
mapper.xml内容:
<?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="DataOperation">
<select id="selectInfo" parameterType="int" resultType="bean.Person">
select * from people where age=#{age};
</select>
<!--调用存储过程-->
<select id="selectPro" parameterType="int" resultType="bean.Person" statementType="CALLABLE">
{call selectPerson(#{age})}
</select>
</mapper>
然后直接运行JAVA代码即可,超简单,没技术含量,最适合初学者