resources:
在【jdbc.properties】中配置 c3p0 数据库连接池:
jdbc.driver=com.mysql.jdbc.Driver # 数据库地址 jdbc.url=jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8 # 用户名 jdbc.username=root # 密码 jdbc.password=root # 最大连接数 c3p0.maxPoolSize=30 # 最小连接数 c3p0.minPoolSize=10 # 关闭连接后不自动commit c3p0.autoCommitOnClose=false # 获取连接超时时间 c3p0.checkoutTimeout=10000 # 当获取连接失败重试次数 c3p0.acquireRetryAttempts=2
在【spring-mybatis.xml】中完成 spring 和 mybatis 的配置:
<?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:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 扫描service包下所有使用注解的类型 --> <context:component-scan base-package="com.ray.service"/> <!-- 配置数据库相关参数properties的属性:${url} --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 数据库连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="maxPoolSize" value="${c3p0.maxPoolSize}"/> <property name="minPoolSize" value="${c3p0.minPoolSize}"/> <property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/> <property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/> <property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/> </bean> <!-- 配置SqlSessionFactory对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource"/> <!-- 配置MyBaties全局配置文件:mybatis-config.xml --> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!-- 扫描entity包 使用别名 --> <property name="typeAliasesPackage" value="com.ray.entity"/> <!-- 扫描sql配置文件:mapper需要的xml文件 --> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- 给出需要扫描Dao接口包 --> <property name="basePackage" value="com.ray.dao"/> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置基于注解的声明式事务 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
在【spring-mvc.xml】中完成 Spring MVC 的相关配置:
<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 扫描web相关的bean --> <context:component-scan base-package="com.ray.controller"/> <!-- 开启SpringMVC注解模式 --> <mvc:annotation-driven/> <!-- 静态资源默认servlet配置 --> <mvc:default-servlet-handler/> <!-- 配置jsp 显示ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
在【logback.xml】中完成日志输出的相关配置:
<?xml version="1.0" encoding="UTF-8"?> <configuration debug="true"> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <root level="debug"> <appender-ref ref="STDOUT"/> </root> </configuration>
以上就完成了 SSM 框架的基本配置:
- 添加进了 SSM 项目所需要的 jar 包
- 配置好了 spring/mybatis/spring MVC 的相关配置信息(自动扫描
com.ray
包下的带有注解的类) - 通过 xml 配置的方式配置好了日志和数据库
⑤ 实体类设计
实体类仅仅是对数据库中表的一一映射(表中字段名应该和实体类中的名称一一对应),同时可能还需要兼顾对业务能力的支持。
- 在 Packge【com.ray.entity】下创建 Student 类:
package com.ray.entity; import java.util.Date; /** * @author Ray * @date 2018/5/27 0027 * Student 实体类 * 表中字段名应该和实体类中的名称一一对应 */ public class Student { private int id; private int student_id; private String name; private int age; private String sex; private Date birthday; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getStudent_id() { return student_id; } public void setStudent_id(int student_id) { this.student_id = student_id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { return "Student{" + "id=" + id + ", student_id=" + student_id + ", name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + ", birthday=" + birthday + '}'; } }
DAO 类的设计
DAO,即 Date Access Object,数据库访问对象,就是对数据库相关操作的封装,让其他地方看不到 JDBC 的代码。
在【com.ray.dao】包下创建【StudentDao】接口:
/** * @author Ray * @date 2018/5/27 0027 * DAO,即 Date Access Object,数据库访问对象 * 对数据库相关操作的封装 */ public interface StudentDao { int getTotal(); //查询数据条目 void addStudent(Student student); //增加一条数据 void deleteStudent(int id); //删除一条数据 void updateStudent(Student student); //更新一条数据 Student getStudent(int id); //根据id查询一条数据 List<Student> list(int start,int count); //查询从start位置开始的count条数据 }
然后在【resources/mapper】下创建好对应的映射文件【StudengDao.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"> <!-- 将namespace的值设置为DAO类对应的路径 --> <mapper namespace="com.ray.dao.StudentDao"> <resultMap id="student" type="student"> <id column="id" property="id"/> <result column="student_id" property="student_id"/> <result column="name" property="name"/> <result column="age" property="age"/> <result column="sex" property="sex"/> <result column="birthday" property="birthday" javaType="java.sql.Date"/> </resultMap> <!-- 查询数据条目 --> <select id="getTotal" resultType="int"> SELECT COUNT(*) FROM student </select> <!-- 增加一条数据 --> <insert id="addStudent" parameterType="Student"> INSERT INTO student VALUES (NULL , #{student_id}, #{name}, #{age}, #{sex}, #{birthday}) </insert> <!-- 删除一条数据 --> <delete id="deleteStudent" parameterType="int"> DELETE FROM student WHERE id = #{id} </delete> <!-- 更新一条数据 --> <update id="updateStudent" parameterType="Student"> UPDATE student SET student_id = #{student_id}, name = #{name}, age = #{age}, sex = #{sex}, birthday = #{birthday} WHERE id = #{id} </update> <!-- 根据id查询一条数据 --> <select id="getStudent" resultMap="student" parameterType="int"> SELECT * FROM student WHERE id = #{id} </select> <!-- 查询从start位置开始的count条数据 --> <select id="list" resultMap="student"> SELECT * FROM student ORDER BY student_id ASC LIMIT #{param1},#{param2} </select> </mapper>
编写好了 Dao 类是需要测试的
在【cn.ray.dao】包下创建【BaseTest】类:
/** * @author Ray * @date 2018/5/27 0027 * 配置spring和junit整合,junit启动时加载springIOC容器 spring-test,junit */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring/spring-*.xml"}) public class BaseTest { }
在【cn.ray.dao】包下创建【BaseDaoTest】类:
/** * @author Ray * @date 2018/5/27 0027 */ public class StudentDaoTest extends BaseTest { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private StudentDao studentDao; /** * 查询数据条目 */ @Test public void getTotal() { int count; count = studentDao.getTotal(); System.out.println(count); } /** * 增加数据 */ @Test public void addStudent() { for (int i = 0; i < 20; i++){ Student student = new Student(); student.setStudent_id(i); student.setName("Ray" + i); student.setSex("男"); student.setAge(17 + i); student.setBirthday(new Date()); studentDao.addStudent(student); } } /** * 删除一条数据 */ @Test public void deleteStudent() { studentDao.deleteStudent(1); } /** * 更新一条数据 */ @Test public void updateStudent() { Student student = new Student(); student.setId(1); student.setStudent_id(3); student.setName("Ray3"); student.setSex("男"); student.setAge(18); student.setBirthday(new Date()); studentDao.updateStudent(student); } /** * 根据id查询一条数据 */ @Test public void getStudent() { Student student = studentDao.getStudent(1); System.out.println(student); } @Test public void list() { }