回到正事!該基于SSM的系統(tǒng)直接用的是上一篇文章的數(shù)據(jù)庫,懶得創(chuàng)建了。整個工程目錄以及數(shù)據(jù)表如下:

效果圖我就不貼出來了,界面跟上一篇貼出來的都一樣,我只是把框架給換了,在jsp中把所有Struts的標(biāo)簽都換成spring提供的form標(biāo)簽!<?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:/software/MySQL-connector/mysql-connector-java-5.1.39-bin.jar" /> <context id="context"> <!-- 為了防止生成的代碼中有很多注釋,比較難看,加入下面的配置控制 --> <commentGenerator> <property name="suppressAllComments" value="true" /> <property name="suppressDate" value="true" /> </commentGenerator> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/forum" userId="root" passWord="5845201314" /> <!-- 生成模型的包名和位置 --> <javaModelGenerator targetPackage="model" targetProject="Forum_SSM" /> <!-- 生成的映射文件包名和位置 --> <sqlMapGenerator targetPackage="mapper" targetProject="Forum_SSM" /> <!-- 生成DAO的包名和位置 --> <javaClientGenerator targetPackage="mapper" targetProject="Forum_SSM" type="XMLMAPPER" /> <!-- 數(shù)據(jù)庫名以及對應(yīng)的表 --> <table schema="forum" tableName="person"> </table> </context></generatorConfiguration>2、相關(guān)配置文件
2.1、web.xml
這里主要配置了Spring的DispatcherServlet,讓它攔截所有以.do結(jié)尾的請求,還配置了一個字符過濾器,防止亂碼問題(個人習(xí)慣了,不管有沒有用,加上去再說)<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>Forum_SSM</display-name> <!-- spring配置文件加載 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- mvc控制器 --> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:mvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- 字符編碼過濾器 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>characterEncoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>enabled</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>2.2、applicationContext.xml
component-scan標(biāo)簽?zāi)J(rèn)情況下自動掃描指定路徑下的包(含所有子包),將帶有@Component、@Repository、@Service、@Controller標(biāo)簽的類自動注冊到spring容器。對標(biāo)記了@Required、@Autowired等注解的類進(jìn)行對應(yīng)的操作使注解生效。
<?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:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <bean id="exceptionHandler" class="exception.ForumExceptionHandler" /> <!-- 掃描DAO和SERVICE包,controller包在springmvc中掃描 --> <context:component-scan base-package="ServiceImpl,DAOImpl" /> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <!-- 定義數(shù)據(jù)源 --> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/forum?characterEncoding=UTF-8"></property> <property name="username" value="root"></property> <property name="password" value="5845201314"></property> </bean> <!-- 會話工廠 :session 工廠可以使用 SqlSessionFactoryBuilder 來創(chuàng)建。而在 MyBatis-spring 中,則使用 SqlSessionFactoryBean 來替代 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 當(dāng)SqlSessionFactoryBean提供的配置不能滿足使用時,你可以使用mybatis-config.xml配置文件配置其他屬性 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> </bean> <!-- 事務(wù)管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置事務(wù)的傳播特性 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <!-- 指定具體需要攔截的方法 --> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED"></tx:method> <tx:method name="delete*" propagation="REQUIRED"></tx:method> <tx:method name="update*" propagation="REQUIRED"></tx:method> <tx:method name="select*" propagation="SUPPORTS"></tx:method> </tx:attributes> </tx:advice> <!-- 配置哪些類的哪些方法參與事務(wù) --> <aop:config> <aop:pointcut id="serviceCut" expression="execution(public * Service.*.*(..))" /> <aop:advisor pointcut-ref="serviceCut" advice-ref="transactionAdvice" /> </aop:config> <!-- spring和mybatis的整合 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="mapper" /> </bean></beans>2.3、SpringMVC配置文件——mvc-config.xml
該配置文件主要服務(wù)于SpringMVC流程。在mvc-config.xml中,最重要的工作是控制轉(zhuǎn)發(fā),這個配置文件中做了最簡單的轉(zhuǎn)發(fā)操作,只能轉(zhuǎn)發(fā)頁面,如果想要通過Ajax實(shí)現(xiàn)轉(zhuǎn)發(fā)數(shù)據(jù),那么需要重寫ViewResolver來實(shí)現(xiàn)這個功能。把jsp文件放在WEB-INF下,這樣就只能通過Controller進(jìn)行訪問。<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"> <!-- 掃描controller包 --> <context:component-scan base-package="Controller"></context:component-scan> <!-- 完成請求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <!-- 配置JSP前綴后綴 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> <!--攔截器 --> <mvc:interceptors> <!--多個攔截器,順序執(zhí)行 --> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="Interceptor.LoginInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> <!-- 支持文件上傳 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> </bean></beans>2.4、mybatis-config.xml
在mybatis-config.xml中不需要額外的配置,它只是個空文件。3、用戶模塊
3.1、Person.java
mybatis的實(shí)體類和hibernate實(shí)體類的不同是mybatis的實(shí)體類不需要加載到spring的beanFactory中,而是通過操作數(shù)據(jù)庫的mapper來持久化數(shù)據(jù)。package model;public class Person { private Integer id; private Date datecreated; private Boolean deleted; private Integer version; private String account; private String birthday; private Date datelastactived; private String email; private String ipcreated; private String iplastactived; private String name; private String password; private String sex; //省略setter和getter方法}3.2、PersonMapper映射接口
對Mybatis-Generator生成的personMapper.java進(jìn)行刪減,只留下在該系統(tǒng)中可能用到的,并添加需要用到的操作方法。package mapper;public interface PersonMapper { Person getPerson(Person person); Person selectByAccount(String account); List<Board> selectBoardByPersonId(int id); List<Person> selectAll(); int deleteByBoardId(Integer id); int insertBoardAdministrator(@Param("boardId") int boardId, @Param("personId") int personId); /*以上為自己實(shí)現(xiàn)的方法,保留了下面可能用到的方法*/ int deleteByPrimaryKey(Integer id); int insert(Person record); int insertSelective(Person record); Person selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Person record); int updateByPrimaryKey(Person record);}3.3、PersonMapper.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="mapper.PersonMapper" > <resultMap id="BaseResultMap" type="model.Person" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="dateCreated" property="datecreated" jdbcType="TIMESTAMP" /> <result column="deleted" property="deleted" jdbcType="BIT" /> <result column="version" property="version" jdbcType="INTEGER" /> <result column="account" property="account" jdbcType="VARCHAR" /> <result column="birthday" property="birthday" jdbcType="VARCHAR" /> <result column="dateLastActived" property="datelastactived" jdbcType="TIMESTAMP" /> <result column="email" property="email" jdbcType="VARCHAR" /> <result column="ipCreated" property="ipcreated" jdbcType="VARCHAR" /> <result column="ipLastActived" property="iplastactived" jdbcType="VARCHAR" /> <result column="name" property="name" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> <result column="sex" property="sex" jdbcType="VARCHAR" /> </resultMap> <resultMap id="BoardResultMap" type="model.Board" extends="mapper.BoardMapper.BaseResultMap"> </resultMap> <sql id="Base_Column_List" > id, dateCreated, deleted, version, account, birthday, dateLastActived, email, ipCreated, ipLastActived, name, password, sex </sql> <sql id="Board_Column_List" > id, dateCreated, deleted, version, description, name, replyCount, threadCount, category_id, last_reply_id, last_thread_id </sql> <select id="getPerson" resultMap="BaseResultMap" parameterType="model.Person" > select <include refid="Base_Column_List" /> from person where account=#{account,jdbcType=VARCHAR} and password=#{password,jdbcType=VARCHAR} </select> <select id="selectByAccount" resultMap="BaseResultMap" parameterType="String" > select <include refid="Base_Column_List" /> from person where account = #{account,jdbcType=VARCHAR} </select> <select id="selectBoardByPersonId" resultMap="BoardResultMap" parameterType="java.lang.Integer" > select <include refid="Board_Column_List" /> from board where id in (select board_id from board_administrator where person_id = #{person_id,jdbcType=INTEGER}) </select> <select id="findPersonByBoardId" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from person where id in (select person_id from board_administrator where board_id = #{board_id,jdbcType=INTEGER}) </select> <select id="selectAll" resultMap="BaseResultMap" > select <include refid="Base_Column_List" /> from person where deleted=false </select> <delete id="deleteByBoardId" parameterType="java.lang.Integer" > delete from board_administrator where board_id = #{boardId,jdbcType=INTEGER} </delete> <insert id="insertBoardAdministrator"> insert into board_administrator values (#{boardId}, #{personId}) </insert> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from person where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from person where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="model.Person" > insert into person (id, dateCreated, deleted, version, account, birthday, dateLastActived, email, ipCreated, ipLastActived, name, password, sex) values (#{id,jdbcType=INTEGER}, #{datecreated,jdbcType=TIMESTAMP}, #{deleted,jdbcType=BIT}, #{version,jdbcType=INTEGER}, #{account,jdbcType=VARCHAR}, #{birthday,jdbcType=VARCHAR}, #{datelastactived,jdbcType=TIMESTAMP}, #{email,jdbcType=VARCHAR}, #{ipcreated,jdbcType=VARCHAR}, #{iplastactived,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="model.Person" > insert into person <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="datecreated != null" > dateCreated, </if> <if test="deleted != null" > deleted, </if> <if test="version != null" > version, </if> <if test="account != null" > account, </if> <if test="birthday != null" > birthday, </if> <if test="datelastactived != null" > dateLastActived, </if> <if test="email != null" > email, </if> <if test="ipcreated != null" > ipCreated, </if> <if test="iplastactived != null" > ipLastActived, </if> <if test="name != null" > name, </if> <if test="password != null" > password, </if> <if test="sex != null" > sex, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=INTEGER}, </if> <if test="datecreated != null" > #{datecreated,jdbcType=TIMESTAMP}, </if> <if test="deleted != null" > #{deleted,jdbcType=BIT}, </if> <if test="version != null" > #{version,jdbcType=INTEGER}, </if> <if test="account != null" > #{account,jdbcType=VARCHAR}, </if> <if test="birthday != null" > #{birthday,jdbcType=VARCHAR}, </if> <if test="datelastactived != null" > #{datelastactived,jdbcType=TIMESTAMP}, </if> <if test="email != null" > #{email,jdbcType=VARCHAR}, </if> <if test="ipcreated != null" > #{ipcreated,jdbcType=VARCHAR}, </if> <if test="iplastactived != null" > #{iplastactived,jdbcType=VARCHAR}, </if> <if test="name != null" > #{name,jdbcType=VARCHAR}, </if> <if test="password != null" > #{password,jdbcType=VARCHAR}, </if> <if test="sex != null" > #{sex,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="model.Person" > update person <set > <if test="datecreated != null" > dateCreated = #{datecreated,jdbcType=TIMESTAMP}, </if> <if test="deleted != null" > deleted = #{deleted,jdbcType=BIT}, </if> <if test="version != null" > version = #{version,jdbcType=INTEGER}, </if> <if test="account != null" > account = #{account,jdbcType=VARCHAR}, </if> <if test="birthday != null" > birthday = #{birthday,jdbcType=VARCHAR}, </if> <if test="datelastactived != null" > dateLastActived = #{datelastactived,jdbcType=TIMESTAMP}, </if> <if test="email != null" > email = #{email,jdbcType=VARCHAR}, </if> <if test="ipcreated != null" > ipCreated = #{ipcreated,jdbcType=VARCHAR}, </if> <if test="iplastactived != null" > ipLastActived = #{iplastactived,jdbcType=VARCHAR}, </if> <if test="name != null" > name = #{name,jdbcType=VARCHAR}, </if> <if test="password != null" > password = #{password,jdbcType=VARCHAR}, </if> <if test="sex != null" > sex = #{sex,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="model.Person" > update person set dateCreated = #{datecreated,jdbcType=TIMESTAMP}, deleted = #{deleted,jdbcType=BIT}, version = #{version,jdbcType=INTEGER}, account = #{account,jdbcType=VARCHAR}, birthday = #{birthday,jdbcType=VARCHAR}, dateLastActived = #{datelastactived,jdbcType=TIMESTAMP}, email = #{email,jdbcType=VARCHAR}, ipCreated = #{ipcreated,jdbcType=VARCHAR}, ipLastActived = #{iplastactived,jdbcType=VARCHAR}, name = #{name,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR}, sex = #{sex,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update></mapper>3.4、PersonDAO層及其實(shí)現(xiàn)
本系統(tǒng)繼續(xù)沿用了DAO層和Service層的編程習(xí)慣。package DAO;public interface PersonDAO { public void save(Person person); public int insert(Person person); public Person selectById(int id); public List<Board> selectBoardByPersonId(int id); public List<Person> selectAll(); public Person findPersonByAccount(String account); public Person getPerson(Person person); public int deleteByBoardId(int id); public int insertBoardAdministrator(int boardId, int personId);}package DAOImpl;@Repositorypublic class PersonDAOImpl implements PersonDAO{ @Autowired private PersonMapper personMapper; @Override public Person findPersonByAccount(String account) { return personMapper.selectByAccount(account); } @Override public Person getPerson(Person person) { return personMapper.getPerson(person); } @Override public void save(Person person) { personMapper.updateByPrimaryKeySelective(person); } @Override public int insert(Person person) { return personMapper.insertSelective(person); } @Override public Person selectById(int id) { return personMapper.selectByPrimaryKey(id); } @Override public List<Board> selectBoardByPersonId(int id) { return personMapper.selectBoardByPersonId(id); } @Override public List<Person> selectAll() { return personMapper.selectAll(); } @Override public int deleteByBoardId(int id) { return personMapper.deleteByBoardId(id); } @Override public int insertBoardAdministrator(int boardId, int personId) { return personMapper.insertBoardAdministrator(boardId, personId); }}3.5、PersonService層及其實(shí)現(xiàn)
package Service;public interface PersonService { public void save(Person person); public int insert(Person person); public Person selectById(int id); public List<Person> selectAll(); public List<Board> selectBoardByPersonId(int id); public Person findPersonByAccount(String account); public Person getPerson(Person person); public int deleteByBoardId(int id); public int insertBoardAdministrator(int boardId, int personId);}package ServiceImpl;@Servicepublic class PersonServiceImpl implements PersonService{ @Autowired private PersonDAO personDAO; @Override public Person findPersonByAccount(String account) { return personDAO.findPersonByAccount(account); } @Override public Person getPerson(Person person) { Person newper=new Person(); newper.setAccount(person.getAccount()); newper.setPassword(md5Util.calc(person.getPassword())); return personDAO.getPerson(newper); } @Override public void save(Person person) { personDAO.save(person); } @Override public int insert(Person person) { if(findPersonByAccount(person.getAccount())!=null) throw new RuntimeException("帳號 " + person.getAccount() + " 已經(jīng)存在。"); person.setPassword(MD5Util.calc(person.getPassword())); return personDAO.insert(person); } @Override public Person selectById(int id) { return personDAO.selectById(id); } @Override public List<Board> selectBoardByPersonId(int id) { return personDAO.selectBoardByPersonId(id); } @Override public List<Person> selectAll() { return personDAO.selectAll(); } @Override public int deleteByBoardId(int id) { return personDAO.deleteByBoardId(id); } @Override public int insertBoardAdministrator(int boardId, int personId) { return personDAO.insertBoardAdministrator(boardId, personId); } }3.6、Person控制器
package Controller;@Controllerpublic class PersonController { @Autowired private PersonService personService; @RequestMapping("person_initAdd.do") public ModelAndView initAdd(HttpServletRequest request){ request.setAttribute("title", "用戶注冊"); request.setAttribute("person", new Person()); return new ModelAndView("person/addPerson"); } @RequestMapping("person_add.do") public ModelAndView add(@ModelAttribute Person person, HttpServletRequest request, HttpServletResponse response){ request.setAttribute("title", "用戶注冊"); person.setIpcreated(request.getRemoteAddr()); person.setIplastactived(request.getRemoteAddr()); person.setDatecreated(new Date()); person.setDatelastactived(new Date()); person.setDeleted(false); if (person.getAccount() == null|| person.getAccount().trim().length() == 0) { request.setAttribute("message", "請輸入帳號"); return initAdd(request); } if (person.getPassword() == null|| person.getPassword().trim().length() == 0|| !person.getPassword().equals(request.getParameter("password1"))) { request.setAttribute("message", "密碼不一致"); return initAdd(request); } try { personService.insert(person);//保存到數(shù)據(jù)庫,此時沒有id PersonUtil.setPersonInf(request, response, personService.findPersonByAccount(person.getAccount())); request.setAttribute("message", "注冊成功"); return new ModelAndView("person/success"); } catch (Exception e) { request.setAttribute("message", "注冊失敗,原因:" + e.getMessage()); return initAdd(request); } } @RequestMapping("person_initLogin.do") public ModelAndView initLogin(HttpServletRequest request){ request.setAttribute("person", new Person()); request.setAttribute("title", "用戶登錄"); return new ModelAndView("person/login"); } @RequestMapping("person_login.do") public ModelAndView login(@ModelAttribute Person person,HttpServletRequest request, HttpServletResponse response) throws Exception{ request.setAttribute("title", "用戶登錄"); Person person1=personService.getPerson(person); if (person1 == null) throw new AccountException("用戶名密碼錯誤"); PersonUtil.setPersonInf(request, response, person1); person1.setIplastactived(request.getRemoteAddr()); person1.setDatelastactived(new Date()); personService.save(person1); request.setAttribute("message", "歡迎回來"); return new ModelAndView("person/success"); } @RequestMapping("person_logout.do") public ModelAndView logout(HttpServletRequest request){ request.setAttribute("title", "用戶注銷"); request.getSession(true).setAttribute(PersonUtil.PERSON_INFO, null); request.setAttribute("person", new Person()); return new ModelAndView("person/login"); } @RequestMapping("person_view.do") public ModelAndView view(HttpServletRequest request){ request.setAttribute("title", "查看用戶資料"); int id=Integer.parseInt(request.getParameter("id")); Person person=personService.selectById(id); request.setAttribute("person", person); List<Board> boardList=personService.selectBoardByPersonId(id); request.setAttribute("boardList", boardList); return new ModelAndView("person/viewPerson"); }}4、版面類型模塊
4.1、Category.java
boardList需要自己手動,因?yàn)樗⒉粚儆诒碇械淖侄危壜?lián)查詢時需要用到package model;public class Category { private Integer id; private Date datecreated; private Boolean deleted; private Integer version; private String name; private List<Board> boardList; //省略setter、getter方法}4.2、CategoryMapper映射接口
package mapper;public interface CategoryMapper { List<Category> getList(); Category selectByName(String name); List<Category> getAll(); /*以上為自己實(shí)現(xiàn)的方法,保留了下面可能用到的方法*/ int deleteByPrimaryKey(Integer id); int insert(Category record); int insertSelective(Category record); Category selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Category record); int updateByPrimaryKey(Category record);}4.3、CategoryMapper.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="mapper.CategoryMapper" > <resultMap id="BaseResultMap" type="model.Category" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="dateCreated" property="datecreated" jdbcType="TIMESTAMP" /> <result column="deleted" property="deleted" jdbcType="BIT" /> <result column="version" property="version" jdbcType="INTEGER" /> <result column="name" property="name" jdbcType="VARCHAR" /> </resultMap> <resultMap id="Cate_BoardResultMap" type="model.Category" extends="BaseResultMap"> <collection property="boardList" column="id" select="mapper.BoardMapper.findBoardByCategoryId"></collection> </resultMap> <sql id="Base_Column_List" > id, dateCreated, deleted, version, name </sql> <select id="getList" resultMap="Cate_BoardResultMap" > select <include refid="Base_Column_List" /> from category where deleted = false </select> <select id="selectByName" resultMap="BaseResultMap" parameterType="String" > select <include refid="Base_Column_List" /> from category where name = #{name,jdbcType=VARCHAR} </select> <select id="getAll" resultMap="BaseResultMap" > select <include refid="Base_Column_List" /> from category where deleted = false </select> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from category where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from category where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="model.Category" > insert into category (id, dateCreated, deleted, version, name) values (#{id,jdbcType=INTEGER}, #{datecreated,jdbcType=TIMESTAMP}, #{deleted,jdbcType=BIT}, #{version,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="model.Category" > insert into category <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="datecreated != null" > dateCreated, </if> <if test="deleted != null" > deleted, </if> <if test="version != null" > version, </if> <if test="name != null" > name, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=INTEGER}, </if> <if test="datecreated != null" > #{datecreated,jdbcType=TIMESTAMP}, </if> <if test="deleted != null" > #{deleted,jdbcType=BIT}, </if> <if test="version != null" > #{version,jdbcType=INTEGER}, </if> <if test="name != null" > #{name,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="model.Category" > update category <set > <if test="datecreated != null" > dateCreated = #{datecreated,jdbcType=TIMESTAMP}, </if> <if test="deleted != null" > deleted = #{deleted,jdbcType=BIT}, </if> <if test="version != null" > version = #{version,jdbcType=INTEGER}, </if> <if test="name != null" > name = #{name,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="model.Category" > update category set dateCreated = #{datecreated,jdbcType=TIMESTAMP}, deleted = #{deleted,jdbcType=BIT}, version = #{version,jdbcType=INTEGER}, name = #{name,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update></mapper>4.4、CategoryDAO層及其實(shí)現(xiàn)
package DAO;public interface CategoryDAO { public List<Category> getList(); public int create(Category category); public Category selectByName(String name); public List<Category> getAll();}package DAOImpl;@Repositorypublic class CategoryDAOImpl implements CategoryDAO{ @Autowired private CategoryMapper categoryMapper; @Override public List<Category> getList() { return categoryMapper.getList(); } @Override public int create(Category category) { return categoryMapper.insertSelective(category); } @Override public Category selectByName(String name) { return categoryMapper.selectByName(name); } @Override public List<Category> getAll() { return categoryMapper.getAll(); }}4.5、CategoryService層及其實(shí)現(xiàn)
package Service;public interface CategoryService { public List<Category> getList(); public int create(Category category); public List<Category> getAll();}package ServiceImpl;@Servicepublic class CategoryServiceImpl implements CategoryService{ @Autowired private CategoryDAO categoryDAO; @Override public List<Category> getList() { return categoryDAO.getList(); } @Override public int create(Category category) { if(categoryDAO.selectByName(category.getName())!=null) throw new RuntimeException("類別 " + category.getName() + " 已經(jīng)存在。"); return categoryDAO.create(category); } @Override public List<Category> getAll() { return categoryDAO.getAll(); }}4.6、Category控制層
package Controller;@Controllerpublic class CategoryController { @Autowired private CategoryService categoryService; @RequestMapping("category_list.do") public ModelAndView list(HttpServletRequest request){ request.setAttribute("title", "輕量級 Java EE 論壇程序"); List<Category> categoryList = categoryService.getList(); request.setAttribute("categoryList", categoryList); return new ModelAndView("category/listCategory"); } @RequestMapping("category_initAdd.do") public ModelAndView initAdd(HttpServletRequest request){ request.setAttribute("title", "添加類別"); request.setAttribute("category", new Category()); return new ModelAndView("category/addCategory"); } @RequestMapping("category_add.do") public ModelAndView add(@ModelAttribute Category category, HttpServletRequest request){ request.setAttribute("title", "添加類別"); category.setDatecreated(new Date()); category.setDeleted(false); categoryService.create(category); return new ModelAndView("category/success"); }}好吧!我承認(rèn)老是貼代碼,毫無營養(yǎng)!版面模塊、帖子模塊和回帖模塊的代碼就不貼出來了。如果是我也沒耐心看完,直接下載源碼學(xué)來得更實(shí)際一些。下載源碼
新聞熱點(diǎn)
疑難解答