[入门级] visual studio 2010 mvc4开发,用ibatis作为数据库访问媒介(一)
[入门级] visual studio 2010 mvc4开发,用ibatis作为数据库访问媒介(一)
实现编程环境
安装visual studio 2010,由于mvc4并不是visual studio 2010默认的mvc版本,因此首先需要安装visual studio 2010 service package 1,然后安装mvc4即可,在安装visual studio 2010 service package 1的时候,时间比较长,在安装进度到达中间的部位的时候可能会出现比较长时间的卡壳,需要耐心等待,然后会出现回滚进度,原来以为回滚就意味着安装失败了,结果在耐心的等待下,发现回滚结束后,跳出了迷人的对话框,告知:安装成功。
关于MVC
MVC就是model,view以及control开头字母的缩写,分别表示模型,视图,控制。它指的是一种开发方式,也就是说在开发过程中,为了降低不同部分的偶联程度,于是将整体依据模型,视图以及控制三个方面进行划分。视图表示的就是展现在客户眼中的内容,控制表示的就是客户需要控制的部分,如点击鼠标进行确认等操作,模型包括与视图相关的一些数据结构以及对业务进行处理的操作方式等。为了更好的利用mvc开发框架进行开发,首先在程序设计的时候,就应该将MCV三个方面进行设计好。
整个操作方式类似如下:
user user | | v v control -> model -> view | v database
关于ibatis.net
ibatis是一个用于更方便的将数据库与项目的偶联程度降低的一个框架,如果想要将数据库从mysql改变成sql server,在原项目中并不用花费时间去修改代码,只需要在ibatis配置的相关文件中进行适当的修改即可,并且对于ibatis配置文件修改之后,并不需要对项目进行重新编译生成,直接运行项目,就能够直接应用修改项,这也进一步缩短了数据库变换可能会引起的开发周期的增加。
如何对ibatis.net进行配置呢。首先,需要关心的文件有:IBatisNet.Common.dll,IBatisNet.DataMapper.dll,log4net.dll,provider.config,SqlMap.config,Person.xml。其中前面三个dll文件用于添加到相应项目的引用中,其中对于简单的示例程序,只需要将IBatisNet.DataMapper.dll添加到项目中即可。provider.config包含了不同数据库的类型,为访问提供了接口。SqlMap.config中包含了让ibatis发挥作用的核心内容。额外的xml文件,如Person.xml包含了一定的sql语句,主要是设置“命令”与sql语句的对应关系,类似map的数据结构中key和value之间的关系。
ibatis.net简单运用
首先设定配置文件SqlMap.config
,内部主要包括了数据库连接信息的设定、sql语句映射文件(如,Person.xml)。具体的内容如下:
<?xml version="1.0" encoding="utf-8" ?> <sqlMapConfig xmlns="http://ibatis.apache.org/dataMapper" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<properties resource="database.config"/> <settings>
<setting cacheModelsEnabled="true"/>
<setting useStatementNamespaces="true"/>
</settings> <providers resource="providers.config" /> <database>
<provider name="provider"></provider>
<dataSource name="IbatisDemo" connectionString="host= host;database= {database};username= username;password= {password};" />
</database> <sqlMaps>
<sqlMap resource="Person.xml"/>
</sqlMaps>
</sqlMapConfig>
在文件 databse.config 文件中,主要设定了与数据库相关的一些参数,如host,用户名,密码,采用的数据库名等。如:
<?xml version="1.0" encoding="utf-8" ?>
<settings>
<!-- User application and configured property settings go here.-->
<!-- Example: <add key="settingName" value="settingValue"/> -->
<add key="provider" value="MySql" />
<add key="database" value="ibatisdemo" />
<add key="host" value="localhost" />
<add key="username" value="root" />
<add key="password" value="password" />
</settings>
provider.config 中还用不同的数据库信息,如MySql相关信息:
<provider
name="MySql"
description="MySQL, MySQL provider 6.9.5.0"
enabled="true"
assemblyName="MySql.Data, Version=6.9.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionClass="MySql.Data.MySqlClient.MySqlConnection"
commandClass="MySql.Data.MySqlClient.MySqlCommand"
parameterClass="MySql.Data.MySqlClient.MySqlParameter"
parameterDbTypeClass="MySql.Data.MySqlClient.MySqlDbType"
parameterDbTypeProperty="MySqlDbType"
dataAdapterClass="MySql.Data.MySqlClient.MySqlDataAdapter"
commandBuilderClass="MySql.Data.MySqlClient.MySqlCommandBuilder"
usePositionalParameters="false"
useParameterPrefixInSql="true"
useParameterPrefixInParameter="true"
parameterPrefix="?"
allowMARS="false"
/>
上面中MySQL provider的版本号需要根据自己安装的情况具体调整。具体版本号可以查看MySQLInstallPath/Connector.Net6.9/Assemblies/v4.0/MySql.Data.dll
文件的属性中的详细信息。对于需要选定的数据库,其enabled选项必须改为true。
接着需要介绍的就是Person.xml
中与sql操作相关的内容了。其具体内容如下:
<?xml version="1.0" encoding="utf-8" ?> <sqlMap namespace="Person" xmlns="http://ibatis.apache.org/mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > <alias>
<typeAlias alias="Person" type="IbatisDemo.Person, IbatisDemo" />
</alias>
<resultMaps>
<resultMap id="SelectResult" class="Person">
<result property="Id" column="PER_ID" />
<result property="Name" column="PER_NAME" />
<result property="Age" column="PER_AGE" />
</resultMap>
</resultMaps> <statements>
<select id="SelectAll" resultMap="SelectResult">
select
PER_ID,
PER_NAME,
PER_AGE
from PERSON
</select>
<select id="SelectOnId" parameterClass="int" resultMap="SelectResult">
select
PER_ID,
PER_NAME,
PER_AGE
from PERSON where PER_ID = #Id#
</select>
<insert id="Insert" parameterClass="Person">
insert into PERSON
(PER_ID, PER_NAME, PER_AGE)
values
(#Id#, #Name#, #Age#)
</insert>
<update id ="Update" parameterClass="Person">
update PERSON set
PER_NAME = #Name#,
PER_AGE = #Age#
where PER_ID = #Id#
</update> <delete id="Delete" parameterClass="int">
delete from PERSON
where PER_ID = #value#
</delete>
</statements> </sqlMap>
另外还有一点需要注意的是,ibatis在对数据库进行操作的时候,前提是数据库以及数据库中相关的table已经建立起来了,因此,首先需要在MySql数据库中建立相应的内容,如:
create database ibatisdemo;
create table if not exists `PERSON` (
`PER_ID` bigint not null,
`PER_NAME` varchar(30) not null,
`PER_AGE` tinyint not null,
primary key(PER_ID)
);
最后让我们建立一个简单的console项目,命名为IbatisDemo,来实现利用ibatis对数据库进行操作。
首先,将建立的SqlMap.Config,database.config,providers.config,Person.xml,并将其放入到项目所在文件夹中,
然后将IbatisNetMapper.dll添加到引用中。其次将项目属性中的目标框架设置为:.NET Framework 4
。
建立Person.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace IbatisDemo
{
class Person
{
public Person()
{ }
private long id;
public long Id { get { return id; } set { id = value; } }
private string name;
public string Name { get { return name; } set { name = value; } }
private int age;
public int Age { get { return age; } set { age = value; } }
} }
然后在Program.cs的main函数中进行简单的操作即可。
// program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IBatisNet.DataMapper; namespace IbatisDemo
{
class Program
{
static void Main(string[] args)
{
try
{
/// 创建数据并往数据库中插入数据
Person person = new Person
{
Id = ,
Name = "me",
Age =
};
Mapper.Instance().Insert("Insert", person); /// 查看数据库中的数据
Person personResult = (Person)Mapper.Instance().QueryForObject("SelectOnId", ); Console.WriteLine("ID: " + personResult.Id + "; Name: " + personResult.Name + "; Age: " + personResult.Age); }
finally
{
Mapper.Instance().Delete("Delete", );
}
}
}
}
然而此时直接运行程序,会抛出如下异常:
说是没办法访问:IbatisDemo.Person..cotr()
方法。于是有两种可能,
- 没有成功生成
.ctor
方法 - 运行过程中,没有调用
.ctor
的权限
借用visual studio tools中的IL反汇编程序,将生成的IbatisDemo.exe打开,可以从fig 2中发现在Person类下已经包含了.ctor
函数,那么出现异常的可能原因就是,没有调用.ctor
的权限,于是,将Person类的可访问性更改为public,再次运行程序。
程序成功运行,结果如下:
mvc4开发模版初探
利用visual studio建立默认的mvc4开发模版,然后逐一分析各个文件的作用。
首先打开visual studio新建项目,在项目中选择mvc4 web application项目,在里面的template中有Empty,Basic,Internet Application等,选择Internet Application,可以更好的查看内部的相关实现。
MvcIbatisDemo项目建立之后,可以看到,项目的文件夹列表有:
- App_Start
- Content 该目录中存储了控制style的css文件,以及相应的图
- Controllers 用于存放控制器相关的内容
- Filters 用来自定义标签属性,如控制变量的范围等
- Images 存储了website使用的图
- Models 用于存放与业务数据,以及具体处理相关的内容
- Scripts 主要用于存储javascript脚本
- Views 用于存放试图相关的内容,试图内容的修改,不用重新编译就能够直接在浏览器的页面中显示出来
因此可见上面的内容中,最为主要的目录有:Controllers,Models,Views,分别用来放置与控制器,模型,以及视图相关的内容。
下面将上述ibatis的相应设置,添加到该项目中,并实现了对数据库的简单操作。不包括用户的登入以及注册。
Models
模型可以分为:数据模型,用来表示数据库中的数据对象;业务模型,表示业务规则,或者具体的操作过程(如,计算购买的物品的总价格),业务模型可以从数据库中读取数据,以及存储数据;视图模型,包含了从controller传递给view的信息,该模型并不包含任何的操作,只是用来存储视图中需要的数据。
为了更清楚的认识models的功能,这里建立数据模型,命名为Person.cs
Controller
首先将url中的内容进行分离成controller,action和id,{controller}/{action}/{id}
,这是在App_Start/RouteConfig.cs中定义的,并且在该文件中还定义了默认的起始页面defaults: new { controller = "Home", action = "Index", id = UrlParamter.Optional }
接着来看一下,HomeController中Index到底干了什么事情。
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; return View();
}
...
}
可见,其将字符串信息赋值给了ViewBag.Message,并且返回视图文件,也就是Views中的内容,其中ViewBag能够在View视图中调用,起到View和Controller之间的数据传递的作用。
Views
Views中的目录结构是:{Views}/{Controller}/{Action}.cshtml
,查看Home下的Index.cshtml文件,如下:
@{
ViewBag.Title = "Home Page";
}
@section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
<h2>@ViewBag.Message</h2>
</hgroup>
<p>
To learn more about ASP.NET MVC visit
<a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
The page features <mark>videos, tutorials, and samples</mark> to help you get the most from ASP.NET MVC.
If you have any questions about ASP.NET MVC visit
<a href="http://forums.asp.net/1146.aspx/1?MVC" title="ASP.NET MVC Forum">our forums</a>.
</p>
</div>
</section>
}
<h3>We suggest the following:</h3>
<ol class="round">
<li class="one">
<h5>Getting Started</h5>
...
</li>
...
</ol>
其中,@section featured {...}
中的内容,是在调用模版文件Views/Shared/_Layout.cshtml
时,替换掉@RenderSection("featured", required: false)
的内容。下面正文中的内容,则是用来替换模版文件中@RenderBody()
内容的部分。
为了举例,在mvc中,使用ibatis,首先在Controller中建立控制文件DemoController.cs
,并将index action中的内容改为如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcIbatisDemo.Models;
using IBatisNet.DataMapper; namespace MvcIbatisDemo.Controllers
{
public class DemoController : Controller
{
//
// GET: /Demo/ public ActionResult Index()
{
/// 注意:通常,在controller中,并不能出现直接调用数据库的语句
/// 而这里,为了简化示例程序,于是直接进行调用
IList<Person> persons = Mapper.Instance().QueryForList<Person>("SelectAll", null); return View(persons);
} }
}
然后,先按快捷键 ctrl-shift-B,再Index内右键,选择添加 Add View,选择 Create a strongly-typed view,在 Model class中选择Person, Scaffold template选择 List。这里首先进行项目建立的原因是,项目建立之后,models中建立的类才会出现在Model Class选项中,具体如下图:
然后,将建立的Index.cshtml中
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
三行内容删除。为了结果能够直接在运行后查看到,将首页默认的路径进行更改,改为:defaults: new { controller = "Demo", action = "Index", id = UrlParameter.Optional }
。运行可以查看结果。显示的结果没有任何的人物信息,因为我们还没有进行创建,于是,还要建立信息创建相关的内容。
在DemoController中添加Create Action。用相似的方法,建立对应的View文件,但是在scaffold template中选择Create。
在Create.cshtml中,默认不会添加ID的输入选项,由于表格建立的时候,id字段并没有auto increment属性,于是增加id的输入框。由于表格提交,采用的post方式,于是在DemoController中,需要建立对应的处理。
[HttpPost]
public ActionResult Create(Person person)
{
if (ModelState.IsValid)
{
Mapper.Instance().Insert("Insert", person);
return RedirectToAction("Index");
} ModelState.AddModelError("", "Creat Person Error");
return View();
}
输入界面为:
点击create后的显示结果为:
下一篇预告
在下一篇文章中将会建立一个简单的《图书管理系统》,并对其进行适当的优化。
[入门级] visual studio 2010 mvc4开发,用ibatis作为数据库访问媒介(一)的更多相关文章
- [入门级] 基于 visual studio 2010 mvc4 的图书管理系统开发初步 (二)
[入门级] 基于 visual studio 2010 mvc4 的图书管理系统开发初步 (二) Date 周六 10 一月 2015 By 钟谢伟 Category website develop ...
- 在 Visual Studio 2010 中开发和部署 Windows Azure 应用程序
原文 在 Visual Studio 2010 中开发和部署 Windows Azure 应用程序 在 Visual Studio 2010 中开发和部署 Windows Azure 应用程序 Jim ...
- 用C#语言在Visual Studio 2010里开发一个自定义的PowerShell Cmdlet
1. 打开Visual Studio 2010 2. 新建一个基于Class Library的项目 3. 给项目起个名字然后OK 4. 为项目添加下列Reference System.Manageme ...
- Visual Studio 2010 旗舰版安装图解
微软发布了最新的 Visual Studio 2010 软件开发编程平台及 .Net Framework 4 框架.这次 VisualStudio 2010 包括 Professional 专业版.P ...
- Visual Studio 2010 集成 SP1 补丁 制作 Visual Studio 2010 Service Pack 1 完整版安装光盘的方法
Now that Visual Studio 2010 SP1 has been released, administrators and developers may wish to install ...
- Microsoft Visual Studio 2010导致系统C盘不断增大问题处理。
一直用Microsoft Visual Studio 2010做开发,发现最近C盘空间是越来越小,一开始以为是IE或者一些系统补丁造成的临时文件,但是使用360,windows优化大师之类的软件都清过 ...
- SharePoint 2010中使用Visual Studio 2010进行方便快速的Web Part开发
转:http://www.cnblogs.com/fatwhale/archive/2010/02/24/1672633.html 在Visual Studio 2010中, 已经集成了用于Shar ...
- Visual Studio 2010 中的 Web 开发
概述 Microsoft Visual Studio 2010 为 ASP.NET Web 应用程序的开发提供非常多新的功能.这些新功能旨在帮助开发者高速方便地创建和部署质量高且功能全的 Web 应用 ...
- 提高你开发效率的十五个Visual Studio 2010使用技巧
提高你开发效率的十五个Visual Studio 2010使用技巧 相信做开发的没有不重视效率的.开发C#,VB的都知道,我们很依赖VS,或者说,我们很感谢VS.能够对一个IDE产生依赖,说明这个ID ...
随机推荐
- BZOJ 1911: [Apio2010]特别行动队 [斜率优化DP]
1911: [Apio2010]特别行动队 Time Limit: 4 Sec Memory Limit: 64 MBSubmit: 4142 Solved: 1964[Submit][Statu ...
- .NET面试题系列[8] - 泛型
“可变性是以一种类型安全的方式,将一个对象作为另一个对象来使用.“ - Jon Skeet .NET面试题系列目录 .NET面试题系列[1] - .NET框架基础知识(1) .NET面试题系列[2] ...
- 如何选择PHP框架?
PHP是世界上最受欢迎的编程语言之—.最近发布的PHP7令这种服务器的编程语言比以前变得更好,更稳定了. PHP被广泛应用于重大的项目.例如Facebook就是使用PHP来维护和创建它们的内部系统的. ...
- Oracle Database 12c Data Redaction介绍
什么是Data Redaction Data Redaction是Oracle Database 12c的高级安全选项之中的一个新功能,Oracle中国在介绍这个功能的时候,翻译为“数据编纂”,在EM ...
- 一个技术汪的开源梦 —— 公共组件缓存之分布式缓存 Redis 实现篇
Redis 安装 & 配置 本测试环境将在 CentOS 7 x64 上安装最新版本的 Redis. 1. 运行以下命令安装 Redis $ wget http://download.redi ...
- Asp.Net 操作XML文件的增删改查 利用GridView
不废话,直接上如何利用Asp.NET操作XML文件,并对其属性进行修改,刚开始的时候,是打算使用JS来控制生成XML文件的,但是最后却是无法创建文件,读取文件则没有使用了 index.aspx 文件 ...
- 缓存工具类CacheHelper
代码: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Syst ...
- 使用apache自带日志分割模块rotatelogs,分割日志
rotatelogs 是 Apache 2.2 中自带的管道日志程序,参数如下(参见:http://lamp.linux.gov.cn/Apache/ApacheMenu/programs/rotat ...
- Linux自动共享USB设备:udev+Samba
一.概述 公司最近要我实现USB设备插入Ubuntu后,自动共享到网络上,能像Windows共享一样(如\\192.168.1.10)访问里面的内容,不需要写入权限.当时听完这需求,我这新人表示惊呆了 ...
- 2016年中国微信小程序专题研究报告
2016年12月29日,全球领先的移动互联网第三方数据挖掘和分析机构iiMedia Research(艾媒咨询)权威首发<2016年中国微信小程序专题研究报告>. 报告显示,82.6%手机 ...