spring.net 实现访问oracle数据库,对表增、删、改、查支持事务拦截
搜索了很多资料终于把spring.net 对oracle的操作实现(winform),并且事务的控制很好。在这里把源码贴出来,方便大家。
spring.net 版本为1.3.1
1:项目引用组件:
其中common.loggin.dll为必要的组件,因为spring.net的相关日志输入都是基于该组件
2:项目结构
实现简单的层级entity、dao、biz、impl、service
3:配置文件
//app.config 文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler,Spring.Core"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler,Spring.Core" />
<section name="parsers" type="Spring.Context.Support.NamespaceParsersSectionHandler, Spring.Core"/>
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
</startup>
<!--Spring.Net节点配置-->
<spring>
<parsers>
<parser type="Spring.Data.Config.DatabaseNamespaceParser, Spring.Data"/>
<parser type="Spring.Transaction.Config.TxNamespaceParser, Spring.Data"/>
</parsers>
<context>
<!--容器配置-->
<resource uri="config://spring/objects"/>
<!--注入spring配置-->
<resource uri="~/config/Objects.xml"/>
</context>
<!--必要的-->
<objects xmlns="http://www.springframework.net"></objects>
</spring>
</configuration>
//Objects.xml 此文件和app.config文件配置的注入文件名称保持一致
<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net"
xmlns:aop = "http://www.springframework.net/aop"
xmlns:db="http://www.springframework.net/database"
xmlns:tx="http://www.springframework.net/tx">
<!--spring.net的事务管理器 但是要用到spring.net自身dao实现-->
<!--<db:provider id="dbProvider"
provider="System.Data.SqlClient"
connectionString="server=数据库地址;database=LeHuoTest;user id=sa;password=Lh123$%^;Pooling=true;Min Pool Size=10;Max Pool Size=50;Connection Lifetime=30;Connection Timeout=30;"/>-->
<!--spring.net访问oracle的配置方法 -->
<db:provider id="dbProviderOracle"
provider="System.Data.OracleClient"
connectionString="Data Source=数据库地址/ORCL;User ID=cvnx2;Password=thinkpad#$#;"/>
<!-- 注入连接 -->
<object id="adoTemplate" type="Spring.Data.Core.AdoTemplate, Spring.Data">
<property name="DbProvider" ref="dbProviderOracle"/>
<property name="DataReaderWrapperType" value="Spring.Data.Support.NullMappingDataReader, Spring.Data"/>
</object>
<!--dao 注入-->
<object id="StudentDao" type="springAdoStudyDao.StudentDao,springAdoStudyDao">
<!--注入 AdoTemplate,名称必须为AdoTemplate,不能改变-->
<property name="AdoTemplate" ref="adoTemplate" />
</object>
<!--impl 注入-->
<object id="StudentImpl" type="springAdoBiz.StudentImpl,springAdoBiz">
<!--name属性为 StudentImpl的属性,必须和StudentImpl类下面的属性保持一致, ref为应用注入-->
<property name="StudentDao" ref="StudentDao"></property>
</object>
<!--service 注入-->
<object id="StudentService" type="springAdoStudyService.StudentService,springAdoStudyService">
<!--name属性为 StudentService的属性,必须和StudentService类下面的属性保持一致, ref为应用注入-->
<property name="StudentImpl" ref="StudentImpl"></property>
</object>
<!--事务管理器-->
<object id="transactionManager"
type="Spring.Data.Core.AdoPlatformTransactionManager, Spring.Data">
<property name="DbProvider" ref="dbProviderOracle"/>
</object>
<!--自定义驱动方式(根据方法的名字判断事务的类型——oracle)-->
<tx:advice id="txAdviceOracle" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" no-rollback-for="ErrorException" rollback-for="BussinessException" isolation="ReadCommitted" timeout="120" />
</tx:attributes>
</tx:advice>
<!--事务切面-->
<tx:attribute-driven/>
</objects>
4:dao访问类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Data.Core;//使用此引用
using System.Data;
using springAdoStudyEntity;
using Spring.Data.Common;
using springAdoStudyDao.utils;
namespace springAdoStudyDao
{
/// <summary>
/// 设置参数oracle为特殊符号: sqlserver是@符号
/// </summary>
public class StudentDao : AdoDaoSupport
{
/// <summary>
/// 创建student表
/// </summary>
public void AddStudentTable()
{
StringBuilder sb = new StringBuilder();
sb.Append("CREATE TABLE Student(");
sb.Append(" id NUMBER(14) NOT NULL,");
sb.Append(" name VARCHAR2(20) NOT NULL,");
sb.Append(" age INT NOT NULL,");
sb.Append(" sex VARCHAR2(2) NOT NULL,");
sb.Append(" mobile VARCHAR2(14) NOT NULL,");
sb.Append(" address VARCHAR2(100) NOT NULL");
sb.Append(" )");
AdoTemplate.ExecuteNonQuery(CommandType.Text, sb.ToString());
}
/// <summary>
/// * 新增学生
/// </summary>
/// <param name="studentObj">学生信息</param>
/// <returns>插入成功或者失败</returns>
public bool AddStudent(StudentEntity studentObj)
{
StringBuilder sql = new StringBuilder();
sql.Append("INSERT INTO STUDENT (ID, NAME, AGE, SEX, MOBILE, ADDRESS)");
sql.Append(" VALUES (:ID, :NAME, :AGE, :SEX, :MOBILE, :ADDRESS)");
IDbParameters p = CreateDbParameters();
p.Add(":ID", DbType.Int64).Value = studentObj.Id;
p.Add(":NAME", DbType.String, 20).Value = studentObj.Name;
p.Add(":AGE", DbType.Int32).Value = studentObj.Age;
p.Add(":SEX", DbType.String, 2).Value = studentObj.Sex;
p.Add(":MOBILE", DbType.String, 14).Value = studentObj.Mobile;
p.Add(":ADDRESS", DbType.String, 100).Value = studentObj.Address;
return AdoTemplate.ExecuteNonQuery(CommandType.Text, sql.ToString(), p) > 0;
}
/// <summary>
/// 修改学生信息
/// </summary>
/// <param name="studentObj">学生信息</param>
/// <returns>修改成功或者失败</returns>
public bool UpdateStudent(StudentEntity studentObj)
{
StringBuilder sql = new StringBuilder();
sql.Append("UPDATE STUDENT a SET a.NAME=:NAME,A.AGE=:AGE,A.SEX=:SEX,A.MOBILE=:MOBILE,A.ADDRESS=:ADDRESS WHERE A.ID=:ID");
IDbParameters p = CreateDbParameters();
p.Add(":ID", DbType.Int64).Value = studentObj.Id;
p.Add(":NAME", DbType.String, 20).Value = studentObj.Name;
p.Add(":AGE", DbType.Int32).Value = studentObj.Age;
p.Add(":SEX", DbType.String, 2).Value = studentObj.Sex;
p.Add(":MOBILE", DbType.String, 14).Value = studentObj.Mobile;
p.Add(":ADDRESS", DbType.String, 100).Value = studentObj.Address;
return AdoTemplate.ExecuteNonQuery(CommandType.Text, sql.ToString(), p) > 0;
}
/// <summary>
/// 删除学生信息
/// </summary>
/// <param name="id">学生ID</param>
/// <returns>删除成功或者失败</returns>
public bool DelStudent(long id)
{
StringBuilder sql = new StringBuilder();
sql.Append("DELETE FROM STUDENT WHERE ID=:ID");
IDbParameters p = CreateDbParameters();
p.Add(":ID",DbType.Int64,14).Value=id;
return AdoTemplate.ExecuteNonQuery(CommandType.Text, sql.ToString(), p) > 0;
}
/// <summary>
/// 获取单个学生信息
/// </summary>
/// <param name="id">学生ID</param>
/// <returns>学生信息</returns>
public StudentEntity GetStudent(long id)
{
StringBuilder sql = new StringBuilder();
sql.Append("SELECT ID, NAME, AGE, SEX, MOBILE, ADDRESS");
sql.Append(" FROM STUDENT WHERE ID=:ID and rownum=1");
IDbParameters p = CreateDbParameters();
p.Add(":ID", DbType.Int64).Value = id;
Object obj = AdoTemplate.QueryWithRowMapperDelegate(CommandType.Text, sql.ToString(), delegate(IDataReader dataRead, int rowNum)
{
StudentEntity entity = new StudentEntity();
entity.Id = dataRead.GetInt64(0);
entity.Name = dataRead.GetString(1);
entity.Age = dataRead.GetInt32(2);
entity.Sex = dataRead.GetString(3);
entity.Mobile = dataRead.GetString(4);
entity.Address = dataRead.GetString(5);
return entity;
}, p);
if(obj!=null){
IList<StudentEntity> list=DataConvertList<StudentEntity>.SpingListConvert(obj as Spring.Collections.LinkedList);
if(list!=null && list.Count>0)
return list[0];
}
return null;
}
/// <summary>
/// 获取所有学生信息
/// </summary>
/// <returns>学生集合</returns>
public IList<StudentEntity> GetStudentList()
{
StringBuilder sql = new StringBuilder();
sql.Append("SELECT ID, NAME, AGE, SEX, MOBILE, ADDRESS");
sql.Append(" FROM STUDENT ");
Object obj= AdoTemplate.QueryWithRowMapperDelegate(CommandType.Text, sql.ToString(), delegate(IDataReader dataRead,int rowNum)
{
StudentEntity entity = new StudentEntity();
entity.Id = dataRead.GetInt64(0);
entity.Name = dataRead.GetString(1);
entity.Age = dataRead.GetInt32(2);
entity.Sex = dataRead.GetString(3);
entity.Mobile = dataRead.GetString(4);
entity.Address = dataRead.GetString(5);
return entity;
});
return DataConvertList<StudentEntity>.SpingListConvert(obj as Spring.Collections.LinkedList);
}
}
}
5:impl层代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using springAdoStudyEntity;
using springAdoStudyDao;
using springAdoBiz.checkException;
using springAdoStudyCommon;
namespace springAdoBiz
{
public class StudentImpl : IStudentBiz
{
private StudentDao StudentDao { get; set; }
/// <summary>
/// 创建student表
/// </summary>
public void AddStudentTable()
{
StudentDao.AddStudentTable();
}
/// <summary>
/// * 新增学生
/// </summary>
/// <param name="studentObj">学生信息</param>
/// <returns>插入成功或者失败</returns>
public bool AddStudent(StudentEntity studentObj)
{
CheckStudentException.Check(studentObj);
StudentEntity model = null;
model = StudentDao.GetStudent(studentObj.Id);
if (model != null)
throw new ErrorException("StudentImpl.AddStudent.E0001", "已存在相同的学生信息,不允许重复添加!");
StudentDao.AddStudent(studentObj);
throw new BussinessException("StudentImpl.AddStudent.B0001", "插入已回滚");
return true;
}
/// <summary>
/// 修改学生信息
/// </summary>
/// <param name="studentObj">学生信息</param>
/// <returns>修改成功或者失败</returns>
public bool UpdateStudent(StudentEntity studentObj)
{
StudentEntity model = null;
model = StudentDao.GetStudent(studentObj.Id);
if (model != null)
throw new Exception("更新失败,记录不存在!");
return StudentDao.UpdateStudent(studentObj);
}
/// <summary>
/// 删除学生信息
/// </summary>
/// <param name="id">学生ID</param>
/// <returns>删除成功或者失败</returns>
public bool DelStudent(long id)
{
StudentEntity model = null;
model = StudentDao.GetStudent(id);
if (model != null)
throw new Exception("删除失败,记录不存在!");
return StudentDao.DelStudent(id);
}
/// <summary>
/// 获取单个学生信息
/// </summary>
/// <param name="id">学生ID</param>
/// <returns>学生信息</returns>
public StudentEntity GetStudent(long id)
{
return StudentDao.GetStudent(id);
}
/// <summary>
/// 获取所有学生信息
/// </summary>
/// <returns>学生集合</returns>
public IList<StudentEntity> GetStudentList()
{
return StudentDao.GetStudentList();
}
}
}
6:service层代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using springAdoBiz;
using springAdoStudyEntity;
using Spring.Transaction.Interceptor;
using springAdoStudyCommon;
namespace springAdoStudyService
{
//如果要使用事务,方法必须使用接口实现才能生效,否则属性StudentImpl会注入失败为NULL
public class StudentService:StudentServiceBiz
{
public StudentImpl StudentImpl{ get; set; }
/// <summary>
/// 创建student表
/// </summary>
public void AddStudentTable()
{
StudentImpl.AddStudentTable();
}
/// <summary>
/// * 新增学生
/// </summary>
/// <param name="studentObj">学生信息</param>
/// <returns>插入成功或者失败</returns>
[Transaction(NoRollbackFor=new Type[]{typeof(ErrorException)},RollbackFor=new Type[]{typeof(BussinessException)})]
public bool AddStudent(StudentEntity studentObj)
{
return StudentImpl.AddStudent(studentObj);
}
/// <summary>
/// 修改学生信息
/// </summary>
/// <param name="studentObj">学生信息</param>
/// <returns>修改成功或者失败</returns>
public bool UpdateStudent(StudentEntity studentObj)
{
return StudentImpl.UpdateStudent(studentObj);
}
/// <summary>
/// 删除学生信息
/// </summary>
/// <param name="id">学生ID</param>
/// <returns>删除成功或者失败</returns>
public bool DelStudent(long id)
{
return StudentImpl.DelStudent(id);
}
/// <summary>
/// 获取单个学生信息
/// </summary>
/// <param name="id">学生ID</param>
/// <returns>学生信息</returns>
public StudentEntity GetStudent(long id)
{
return StudentImpl.GetStudent(id);
}
/// <summary>
/// 获取所有学生信息
/// </summary>
/// <returns>学生集合</returns>
public IList<StudentEntity> GetStudentList()
{
return StudentImpl.GetStudentList();
}
}
}
7:测试类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using springAdoStudyService;
using springAdoStudyEntity;
using springAdoStudyDao;
using springAdoBiz;
using Spring.Context.Support;
namespace springAdoStudyUI
{
class Program
{
static void Main(string[] args)
{
Spring.Context.IApplicationContext context = Spring.Context.Support.ContextRegistry.GetContext();
StudentServiceBiz studentService = context.GetObject("StudentService") as StudentServiceBiz;
#region 增加student表
//studentService.AddStudentTable();
#endregion
#region 加入学生信息 (带事务控制)
try
{
StudentEntity entity = new StudentEntity();
entity.Id = 1001;
entity.Name = "迅雷003";
entity.Age = 20;
entity.Sex = "男";
entity.Mobile = "12434354a6";
entity.Address = "广州天河1";
studentService.AddStudent(entity);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
#endregion
#region 获取单个学生信息
//StudentEntity singleEntity=studentService.GetStudent(1000);
#endregion
#region 获取所有学生列表
//IList<StudentEntity> list = studentService.GetStudentList();
#endregion
#region 更新单个学生信息
//StudentEntity up_entity = new StudentEntity();
//up_entity.Id = 1000;
//up_entity.Name = "迅雷002";
//up_entity.Age = 20;
//up_entity.Sex = "男";
//up_entity.Mobile = "124343545";
//up_entity.Address = "广州天河";
//bool update_success = studentService.UpdateStudent(up_entity);
#endregion
#region 删除单个学生信息
//bool del_success = studentService.DelStudent(1000);
#endregion
Console.Read();
}
}
}
需要源码的可以联系