定制网站报价,凡科电脑版登录首页,吴志国网站建设工作室,网络营销推广方案书作为本教程的第一步#xff08;带有MyBatis 3的Spring MVC 3 CRUD示例#xff09;#xff0c;我们将定义一个MyBatis服务#xff0c;该服务将帮助我们在数据库上执行CRUD操作。 我们有一个用于User的域类和一个用于将User信息存储在数据库中的数据库表。 在示例中#xff… 作为本教程的第一步带有MyBatis 3的Spring MVC 3 CRUD示例我们将定义一个MyBatis服务该服务将帮助我们在数据库上执行CRUD操作。 我们有一个用于User的域类和一个用于将User信息存储在数据库中的数据库表。 在示例中我们将使用xml配置模型来定义将执行CRUD操作的SQL命令。 我们的领域类 package com.raistudies.domain;import java.io.Serializable;public class User implements Serializable{private static final long serialVersionUID 3647233284813657927L;private String id;private String name null;private String standard null;private String age;private String sex null;//setter and getter have been omitted to make the code shortOverridepublic String toString() {return User [name name , standard standard , age age , sex sex ];}
} 我们的域类中有五个属性它们称为User它们必须为其提供数据库服务。 我们的数据库表 以下是我们的数据库表 CREATE TABLE user (id varchar(36) NOT NULL,name varchar(45) DEFAULT NULL,standard varchar(45) DEFAULT NULL,age varchar(45) DEFAULT NULL,sex varchar(45) DEFAULT NULL,PRIMARY KEY (id)
) ENGINEInnoDB DEFAULT CHARSETutf8 创建CRUD操作的界面 为了使用MyBatis 3定义CRUD数据库操作我们必须指定将用于执行CRUD操作的方法。 以下是我们示例的界面 package com.raistudies.persistence;import java.util.List;import com.raistudies.domain.User;public interface UserService {public void saveUser(User user);public void updateUser(User user);public void deleteUser(String id);public ListUser getAllUser();
} 我们这里有四种方法来执行创建更新删除和从数据库获取操作。 UserService接口的XML映射文件 ?xml version1.0 encodingUTF-8?
!DOCTYPE mapper PUBLIC -//mybatis.org//DTD Mapper 3.0//EN
http://mybatis.org/dtd/mybatis-3-mapper.dtdmapper namespacecom.raistudies.persistence.UserServiceresultMap idresult typeuserresult propertyid columnid/result propertyname columnname/result propertystandard columnstandard/result propertyage columnage/result propertysex columnsex//resultMapselect idgetAllUser parameterTypeint resultMapresultSELECT id,name,standard,age,sexFROM user;/selectinsert idsaveUser parameterTypeuserINSERT INTO user (id,name,standard,age,sex)VALUE (#{id},#{name},#{standard},#{age},#{sex})/insertupdate idupdateUser parameterTypeuserUPDATE userSETname #{name},standard #{standard},age #{age},sex #{sex}where id #{id}/updatedelete iddeleteUser parameterTypeintDELETE FROM userWHERE id #{id}/delete
/mapper 您会在这里看到很多新东西 映射文件将包含元素mapper /来定义服务的SQL语句。 在这里属性“ 名称空间 ”定义了已为其定义此映射文件的接口。 insert /标记定义该操作为插入类型。 “ id ”属性的值指定为其定义了SQL语句的函数名称。 这里是“ saveUser ”。 属性“ parameterType ”定义方法的参数是哪种类型。 我们在这里为User类使用了别名。 稍后将在MyBatis配置文件中配置别名。 然后我们必须定义SQL语句。 {id}定义将类User的属性“ id ”作为参数传递给SQL查询。 resultMap /标记用于指定User类和用户表之间的映射。 resultMap /的id是映射定义的唯一名称。 在此标签下我们定义了不同的属性以及将哪个列绑定到哪个属性。 select /标记用于指定选择SQL语句。 “ id ”属性的值指定为其定义了SQL语句的函数名称。 属性resultMap用于将SQL语句的返回类型定义为一个集合。 MyBatis 3配置文件 以下是我们的MyBatis配置文件 ?xml version1.0 encodingUTF-8?
!DOCTYPE configuration
PUBLIC -//mybatis.org//DTD Config 3.0//EN
http://mybatis.org/dtd/mybatis-3-config.dtdconfigurationsettings!-- changes from the defaults --setting namelazyLoadingEnabled valuefalse //settingstypeAliasestypeAlias typecom.raistudies.domain.User aliasuser//typeAliases
/configuration 您可以看到我们尚未在此处定义一些非常重要的属性 数据库连接属性。 与交易相关的属性。 并且也没有定义映射器配置。 MyBatis 3是一个非常强大的SQL映射框架它使用用户定义的服务的代理实现自动生成数据库访问类。 如果您将MyBatis 3与Spring框架集成并使用这些代理实现我们就会意识到这是真正的力量。 这将使我们的数据库工作减少80。 在下面我们将看到如何将MyBatis 3与Spring 3框架集成在一起。 以前我们使用MyBatis 3为User类创建了CRUD数据库服务。现在我们将使用MyBatis与Spring框架集成的数据服务进行集成。 使用的工具 c3p0-0.9.1.2.jar –用于提供池化数据库连接。 mybatis-spring-1.0.0.jar –用于将MyBatis与Spring集成由MyBatis团队提供 Spring JDBC和Core库 要集成这两个框架我们必须遵循以下步骤 步骤1将数据源定义为Spring bean 由于我们将使用c3po数据源提供程序因此我们必须在Spring中定义数据源bean。 以下是配置代码段 !-- Declare a datasource that has pooling capabilities --
bean iddataSource classcom.mchange.v2.c3p0.ComboPooledDataSource
destroy-methodclose p:driverClass${app.jdbc.driverClassName}
p:jdbcUrl${app.jdbc.url} p:user${app.jdbc.username} p:password${app.jdbc.password}
p:acquireIncrement10 p:idleConnectionTestPeriod60 p:maxPoolSize100
p:maxStatements50 p:minPoolSize10 / 在这里我们创建了一个带有com.mchange.v2.c3p0.ComboPooledDataSource类的id dataSource的spring bean它由c3p0库提供用于合并数据源。 我们在bean中设置了一些属性。 以下是在bean中定义的属性的描述 driverClass 将用于连接数据库的驱动程序类。 jdbcUrl jdbc定义数据库连接字符串的URL。 user 数据库用户的用户名。 password 数据库用户的密码。 acquisitionIncrement 在连接短缺的情况下一次将创建多少个连接。 idleConnectionTestPeriod 连接断开多长时间后如果不再使用它它将被关闭。 maxPoolSize 可以创建的最大连接数。 maxStatements 连接上要执行的最大SQL语句数。 minPoolSize 要创建的最小连接数。 我们已经使用Spring EL定义了许多属性值这些属性值将从属性文件中获取。 在Spring定义交易管理器 我们将使用Spring JDBC框架提供的用户事务管理器为了定义事务级别我们将使用注释。 以下是事务管理器的配置 !-- Declare a transaction manager --
bean idtransactionManager
classorg.springframework.jdbc.datasource.DataSourceTransactionManager
p:dataSource-refdataSource /!-- Enable annotation style of managing transactions --
tx:annotation-driven transaction-managertransactionManager / 定义MyBatis SqlSessionFactory和MapperScanner !-- define the SqlSessionFactory, notice that configLocation is not needed when you use MapperFactoryBean --
bean idsqlSessionFactory classorg.mybatis.spring.SqlSessionFactoryBeanproperty namedataSource refdataSource /property nameconfigLocation valueWEB-INF/mybatis/sqlmap-config.xml /
/bean!-- scan for mappers and let them be autowired --
bean classorg.mybatis.spring.mapper.MapperScannerConfigurerproperty namebasePackage value${MapperInterfacePackage} /
/bean SqlSessionFactory bean将提供MyBatis的SessionFactory实例。 要配置SqlSessionFactory我们需要定义两个属性。 首先MyBatis将使用其创建连接数据库的数据源和MyBatis配置文件名来配置MyBatis的环境。 MapperScannerConfigurer用于发布定义为MyBatis的数据服务接口以配置为Spring Bean。 我们只需要提供定义接口及其映射XML文件的程序包即可。 我们可以使用通用分隔符或分号指定多个软件包。 之后我们将能够使用Autowired批注获取UserService的实例。 我们不必实现该接口因为MyBatis将为此提供代理实现。 Spring配置文件一起 这是我们的jdbc-context.xml ?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beans
xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xmlns:phttp://www.springframework.org/schema/p
xmlns:txhttp://www.springframework.org/schema/tx xmlns:contexthttp://www.springframework.org/schema/context
xsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdcontext:property-placeholder location/WEB-INF/jdbc.properties,/WEB-INF/mybatis/mybatis.properties /!-- Enable annotation style of managing transactions --tx:annotation-driven transaction-managertransactionManager /!-- Declare a datasource that has pooling capabilities --bean iddataSource classcom.mchange.v2.c3p0.ComboPooledDataSourcedestroy-methodclose p:driverClass${app.jdbc.driverClassName}p:jdbcUrl${app.jdbc.url} p:user${app.jdbc.username} p:password${app.jdbc.password}p:acquireIncrement10 p:idleConnectionTestPeriod60 p:maxPoolSize100p:maxStatements50 p:minPoolSize10 /!-- Declare a transaction manager --bean idtransactionManagerclassorg.springframework.jdbc.datasource.DataSourceTransactionManagerp:dataSource-refdataSource /!-- define the SqlSessionFactory, notice that configLocation is not needed when you use MapperFactoryBean --bean idsqlSessionFactory classorg.mybatis.spring.SqlSessionFactoryBeanproperty namedataSource refdataSource /property nameconfigLocation valueWEB-INF/mybatis/sqlmap-config.xml //bean!-- scan for mappers and let them be autowired --bean classorg.mybatis.spring.mapper.MapperScannerConfigurerproperty namebasePackage value${MapperInterfacePackage} //bean/beans jdbc.properties文件 # database properties
app.jdbc.driverClassNamecom.mysql.jdbc.Driver
app.jdbc.urljdbc:mysql://localhost/mybatis-example
app.jdbc.usernameroot
app.jdbc.passwordpassword mybatis.properties文件 MapperInterfacePackagecom.raistudies.persistence 参考 使用我们的JCG合作伙伴 使用MyBatis 3映射框架创建CRUD服务-第1部分和集成MyBatis 3和Spring框架-第2部分 Rai Studies博客上的Rahul Mondal。 翻译自: https://www.javacodegeeks.com/2012/02/mybatis-3-spring-integration-tutorial.html