全注解实现SSM 博客分类: 常用框架 SSM全注解搭建
程序员文章站
2024-02-08 15:02:28
...
本文搭建的SSM框架,即Spring,Struts2,MyBatis。本次搭建采用了Maven对项目进行管理
1:建立maven的web项目
2:数据库中新建表,本文中,采用的是mysql数据库
3:进行配置文件的配置
此时,可关注以上配置文件,其中beans.xml是Spring的xml文件,mybatis.xml是Mybatis的配置,struts.xml是struts2的xml文件。generatorConfig是生成mapping,dao和domain的工具,稍后将做介绍。
beans.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:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd"> <!-- 扫描项目中的注解 --> <context:annotation-config /> <context:component-scan base-package="cn.wind" /> <aop:aspectj-autoproxy proxy-target-class="true" /> <!-- c3p0配置 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver" /> <property name="jdbcUrl"> <value><![CDATA[jdbc:mysql:///exm_mybatis?useUnicode=true&characterEncoding=UTF-8]]></value> </property> <property name="user" value="root" /> <property name="password" value="123456" /> <property name="checkoutTimeout" value="3000" /> <property name="maxPoolSize" value="3"></property> </bean> <!-- 创建SqlSessionFactory,同时指定数据源,整合mybatis,装配mapping文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations"> <list> <value>classpath:cn/wind/mapping/*.xml</value> </list> </property> <property name="configLocation" value="classpath:mybatis.xml"></property> </bean> <!-- 自动扫描 将Mapper接口生成代理注入到Spring,实现自动装配 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.wind.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 配置事务管理器 --> <!-- 如果spring与mybatis整合,就直接使用databaseoure的事务就可以了 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 利用aop实现事务的配置 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* cn..service.I*Service.*(..))" id="cut" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="cut" /> </aop:config> </beans>
mybatis.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties> <property name="dialect" value="oracle" /> </properties> <settings> <!--全局映射器启用缓存 --> <!--<setting name="logImpl" value="STDOUT_LOGGING"/> --> <setting name="cacheEnabled" value="true" /> <!--查询时,关闭关联对象即时加载以提高性能 --> <setting name="lazyLoadingEnabled" value="true" /> <!--设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 --> <setting name="aggressiveLazyLoading" value="false" /> <!--对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 --> <setting name="multipleResultSetsEnabled" value="true" /> <!--允许使用列标签代替列名 --> <setting name="useColumnLabel" value="true" /> <!--允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 <setting name="useGeneratedKeys" value="true" /> --> <!--给予被嵌套的resultMap以字段-属性的映射支持 --> <setting name="autoMappingBehavior" value="FULL" /> <setting name="mapUnderscoreToCamelCase" value="true" /> <setting name="defaultExecutorType" value="SIMPLE" /> <!--数据库超过25000秒仍未响应则超时 --> <setting name="defaultStatementTimeout" value="25000" /> </settings> <typeAliases> </typeAliases> </configuration>
struts2.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!-- 自动装配 --> <constant name="struts.objectFactory.spring.autoWire.alwaysRespect" value="true" /> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <package name="onePackage" extends="json-default" namespace="/"> <action name="user" class="cn.wind.action.UserAction"> <result name="success">/jsps/succ.jsp</result> </action> </package> <!-- <include file="struts-demo.xml"></include> --> </struts>
4:利用mybatis-generator-core,全自动生成mapping,domain,dao。本文后面附带此工具,可进行下载使用。另外,generatorConfig.xml可参考如下。在mysql和oracle中均可使用。由于本次构建环境采用的是mysql,故将oracle的配置注释起来了
注:generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 数据库驱动包位置 --> <classPathEntry location="D:\programfiles\.m2\repository\mysql\mysql-connector-java\5.1.34\mysql-connector-java-5.1.34.jar" /> <!-- <classPathEntry location="D:\mybatis-generator\ojdbc14.jar" /> --> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator> <!-- 数据库链接URL、用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/exm_mybatis" userId="root" password="123456"> <!-- <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@xxx.xxx.xxx.xxx:1521:ora10cq" userId="tap_sys" password="tap_sys"> --> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 生成模型的包名和位置 --> <javaModelGenerator targetPackage="cn.wind.domain" targetProject="Demo_SSM_1"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 生成的映射文件包名和位置 --> <sqlMapGenerator targetPackage="cn.wind.mapping" targetProject="Demo_SSM_1"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 生成DAO的包名和位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="cn.wind.dao" targetProject="Demo_SSM_1"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 要生成那些表(更改tableName和domainObjectName就可以) --> <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" /> </context> </generatorConfiguration>
除此之外,还需要oracle或者mysql的驱动包,亦可在本文后面下载
5:实现效果如下:
6:进行service的代码编写
IUserService.java
package cn.wind.service; import cn.wind.domain.User; public interface IUserService { int deleteByPrimaryKey(String id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(String id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); }
UserService.java
package cn.wind.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.wind.dao.UserMapper; import cn.wind.domain.User; // @Service("UserService")给实例化的UserService取名字为UserService @Service("UserService") public class UserService implements IUserService { // 完成自动装配的工作 // 通过 @Autowired的使用来消除 set ,get方法。 @Autowired UserMapper userMapper; @Override public int deleteByPrimaryKey(String id) { userMapper.deleteByPrimaryKey(id); return 0; } @Override public int insert(User record) { userMapper.insert(record); return 0; } @Override public int insertSelective(User record) { userMapper.insertSelective(record); return 0; } @Override public User selectByPrimaryKey(String id) { return userMapper.selectByPrimaryKey(id); } @Override public int updateByPrimaryKeySelective(User record) { userMapper.updateByPrimaryKeySelective(record); return 0; } @Override public int updateByPrimaryKey(User record) { userMapper.updateByPrimaryKey(record); return 0; } }
7:action
package cn.wind.action; import org.springframework.beans.factory.annotation.Autowired; import cn.wind.domain.User; import cn.wind.service.IUserService; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; public class UserAction extends ActionSupport implements ModelDriven<User> { private static final long serialVersionUID = 1L; private User u = new User(); @Override public User getModel() { return u; } @Autowired IUserService userService; @Override public String execute() throws Exception { User user= userService.selectByPrimaryKey("1"); System.out.println("query success:"+user.getName()+","+user.getPwd()); return SUCCESS; } }
8:此时,框架搭建完毕,进行测试。
http://localhost:8080/Demo_SSM_1/user
可以在console查看到查询内容。
这只是简单demo,不再做其他扩展