Mybatis(四)

spring-mybaits-mysql
1)创建一个spring-mybaits-mysql这么一个javaweb或java工程
2)导入spring,mybatis,c3p0,oracle和mybatis提供的与spring整合的插件包
   mysql的jar:
       mysql-connector-java-5.1.7-bin.jar
   oracle的jar:
        ojdbc5.jar
   c3p0的jar:
c3p0-0.9.1.2.jar
   mybatis的jar:
asm-3.3.1.jar        
cglib-2.2.2.jar
commons-logging-1.1.1.jar       
mybatis-3.1.1.jar
  mybatis与spring整合的jar
       mybatis-spring-1.1.1.jar
 spring的ioc模块的jar:
       org.springframework.asm-3.0.5.RELEASE.jar
       org.springframework.beans-3.0.5.RELEASE.jar
       org.springframework.context-3.0.5.RELEASE.jar
       org.springframework.core-3.0.5.RELEASE.jar
        org.springframework.expression-3.0.5.RELEASE.jar
        commons-logging.jar
spring的aop模块的jar:
        aopalliance.jar
        aspectjweaver.jar
        cglib-2.2.2.jar
       org.springframework.aop-3.0.5.RELEASE.jar
  spring的transaction模块的jar:
       org.springframework.jdbc-3.0.5.RELEASE.jar
       org.springframework.orm-3.0.5.RELEASE.jar
       org.springframework.transaction-3.0.5.RELEASE.jar
3)创建students.sql
--mysql
create table students(
   sid int(5) primary key,
   sname varchar(10),
   ssal double(8,2)
);


4)创建Student.java
public class Student {
private Integer id;//编号
private String name;//姓名
private Double sal;//薪水
public Student(){}
public Student(Integer id, String name, Double sal) {
this.id = id;
this.name = name;
this.sal = sal;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getSal() {
return sal;
}
public void setSal(Double sal) {
this.sal = sal;
}
}


5)创建StudentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="studentNamespace">
<resultMap type="cn.itcast.javaee.mybatis.entity.Student"id="studentMap">
<id property="id" column="sid" />
<result property="name" column="sname"/>
<result property="sal" column="ssal"/>
</resultMap>
<insert id="insert"parameterType="cn.itcast.javaee.mybatis.entity.Student">
insert into students(sid,sname,ssal)values(#{id},#{name},#{sal})
</insert>
</mapper>


6)创建StudentDao.java
public class StudentDao {
private SqlSessionFactory sqlSessionFactory;
public void setSqlSessionFactory(SqlSessionFactorysqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
public void insert(Student student){
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.insert("studentNamespace.insert",student);
//int i = 10/0;
}
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext(newString[]{"spring.xml"});
StudentDao studentDao = (StudentDao)ac.getBean("studentDaoID");
studentDao.insert(new Student(1,"哈哈",7000D));
}
}


7)在src目录下创建mybatis.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<mapperresource="cn/itcast/javaee/mybatis/entity/StudentMapper.xml"/>
</mappers>
</configuration>


8)在src目录下创建spring.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:context="http://www.springframework.org/schema/context"
     xmlns:aop="http://www.springframework.org/schema/aop"
     xmlns:tx="http://www.springframework.org/schema/tx"
 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.0.xsd
 
 http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-3.0.xsd
   
 http://www.springframework.org/schema/aop 
 http://www.springframework.org/schema/aop/spring-aop-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/mvc
     http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

      <!--配置C3P0连接池(即管理数据库连接) -->
      <beanid="comboPooledDataSourceID"class="com.mchange.v2.c3p0.ComboPooledDataSource">
     <property name="driverClass" value="com.mysql.jdbc.Driver"/>
     <property name="jdbcUrl"value="jdbc:mysql://127.0.0.1:3306/mybatis"/>
     <property name="user" value="root"/>
     <property name="password" value="root"/>
     </bean>
     
      <!--配置SqlSessionFactoryBean(即替代MyBatisUtil工具类的作用) -->
      <beanid="sqlSessionFactoryBeanID"class="org.mybatis.spring.SqlSessionFactoryBean">
     <property name="dataSource" ref="comboPooledDataSourceID"/>
     <property name="configLocation"value="classpath:mybatis.xml"/>
     </bean>
     
      <!--配置事务管理器(即使用JDBC事务管理器) -->
      <beanid="dataSourceTransactionManagerID"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     <property name="dataSource" ref="comboPooledDataSourceID"/>
     </bean>
     
      <!--配置事务通知(即哪些方法需要事务) -->
 <tx:advice id="tx"transaction-manager="dataSourceTransactionManagerID">
  <tx:attributes>
  <tx:method name="*"propagation="REQUIRED"/>
  </tx:attributes>
 </tx:advice>    

      <!--配置事务切面(即哪些包中的类需要事务通知) -->
     <aop:config>
     <aop:pointcut id="pointcut" expre ssion="execution(*cn.itcast.javaee.mybatis.dao.*.*(..))"/>
     <aop:advisor advice-ref="tx" pointcut-ref="pointcut" />
     </aop:config>
     
     
      <!--配置StudentDao类 -->
      <beanid="studentDaoID"class="cn.itcast.javaee.mybatis.dao.StudentDao">
     <property name="sqlSessionFactory"ref="sqlSessionFactoryBeanID"/>
     </bean>
     
</beans>


9)测试类
public class TestEmpDao {

@Test
public void test2() throws Exception {
ApplicationContext ac = newClassPathXmlApplicationContext(
new String[] { "spring.xml" });
EmpDao empDao = (EmpDao) ac.getBean("empDaoID");
empDao.add(new Emp(3, "明明", 8000, "男"));
}
}

jsp/js/jquery/easyui/json + @springmvc + spring + mybatis  + mysql/oracle开发
由上面的学生管理改变



1)员工管理系统--增加员工
regist.jsp:
<body>
<table border="2" align="center">
<tr>
<th>编号</th>
<td><input type="text" name="id"></td>
</tr>
<tr>
<th>姓名</th>
<td><input type="text" name="name"></td>
</tr>
<tr>
<th>薪水</th>
<td><input type="text" name="sal"></td>
</tr>
<tr>
<th>性别</th>
<td>
<input type="radio" name="sex" value="男"/>男
<input type="radio" name="sex" value="女" checked/>女
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="注册"/>
</td>
</tr>
</table>
  </body>



2)配置web.xml
<!-- 核心springmvc核心控制器 -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<!-- POST编码过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>


@RequestMapping(value="/register")
public String registerMethod(Emp emp) throws Exception{
//调用业务层
empService.register(emp);
return "success";
}
}


4)业务层
public class EmpService {
private EmpDao empDao;
public void setEmpDao(EmpDao empDao) {
this.empDao = empDao;
}

public void register(Emp emp) throws Exception{
empDao.add(emp);
}
}


5)配置spring.xml
<!-- 注册EmpService -->
     <beanid="empServiceID"class="cn.itcast.javaee.mybatis.service.EmpService">
     <property name="empDao" ref="empDaoID"></property>
    </bean>
     
     <!--注册EmpAction -->
    <context:component-scanbase-package="cn.itcast.javaee.mybatis.action"/>


<!-- 通知springioc容器这些注解的作用 -->
<context:annotation-config/>
<!-- 视图解析器 -->
      <beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
     <property name="prefix" value="/jsp/"/>
     <property name="suffix" value=".jsp"/>
     </bean>
6)添加/jsp/success.jsp文件



9 逆向工程
9.1 什么是逆向工程
mybaits需要程序员自己编写sql语句,mybatis官方提供逆向工程可以针对单表自动生成mybatis执行所需要的代码(mapper.java,mapper.xml、po..)
企业实际开发中,常用的逆向工程方式:
由于数据库的表生成java代码。
9.2 下载逆向工程

9.3 使用方法(会用)
9.3.1 运行逆向工程 

建议使用java程序方式,不依赖开发工具。
9.3.2 生成代码配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatisGenerator Configuration 1.0//EN"
 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">


<generatorConfiguration>
<context id="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis"userId="root"
password="mysql">
</jdbcConnection>
<!-- <jdbcConnectiondriverClass="oracle.jdbc.OracleDriver"
connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg" 
userId="yycg"
password="yycg">
</jdbcConnection> -->


<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为true时把JDBC DECIMAL 和 
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
</javaTypeResolver>


<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="cn.itcast.ssm.po"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
       <!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGeneratortargetPackage="cn.itcast.ssm.mapper" 
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="cn.itcast.ssm.mapper" 
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<table tableName="items"></table>
<table tableName="orders"></table>
<table tableName="orderdetail"></table>
<table tableName="user"></table>


</context>
</generatorConfiguration>




9.3.3 执行生成程序
public class GeneratorSqlmap {
public void generator() throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//指定 逆向工程配置文件
File configFile = newFile("generatorConfig.xml"); 
ConfigurationParser cp = newConfigurationParser(warnings);
Configuration config =cp.parseConfiguration(configFile);
DefaultShellCallback callback = newDefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = newMyBatisGenerator(config,
callback, warnings);
myBatisGenerator.generate(null);
} 
public static void main(String[] args) throws Exception{
try {
GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
}



生成后的代码:


9.3.4 使用生成的代码
需要将生成工程中所生成的代码拷贝到自己的工程中。
测试ItemsMapper中的方法
//自定义条件查询
@Test
public void testSelectByExample() {
ItemsExample itemsExample = new ItemsExample();
//通过criteria构造查询条件
ItemsExample.Criteria criteria =itemsExample.createCriteria();
criteria.andNameEqualTo("笔记本3");
//可能返回多条记录
List<Items> list =itemsMapper.selectByExample(itemsExample);
System.out.println(list);
}
//根据主键查询
@Test
public void testSelectByPrimaryKey() {
Items items = itemsMapper.selectByPrimaryKey(1);
System.out.println(items);
}

//插入
@Test
public void testInsert() {
//构造 items对象
Items items = new Items();
items.setName("手机");
items.setPrice(999f);
itemsMapper.insert(items);
}
//更新数据
@Test
public void testUpdateByPrimaryKey() {
//对所有字段进行更新,需要先查询出来再更新
Items items = itemsMapper.selectByPrimaryKey(1);
items.setName("水杯");
itemsMapper.updateByPrimaryKey(items);
//如果传入字段不空为才更新,在批量更新中使用此方法,不需要先查询再更新
//itemsMapper.updateByPrimaryKeySelective(record);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值