MyBatisだけを使用して物事を管理します
MyBatisの記事に関連するコンテンツを書きました。ここでは、最も簡単なデモを書き続けます。以前にMyBatisの内容を確認しましょう。まず、テーブルを作成し、シンプルな学生テーブルを作成します。
テーブル学生を作成する(Student_id int auto_increment、suduent_name varchar(20)not null、primary key(desudent_id))
Entity Class Student.javaを作成:
パブリッククラスの学生{private int studentid; private string studentname; public int getstudentid(){return studentid;} public void setStudentid(int studentid){this.studentid = dustentid;} public string getstudentname(){return sudentname;} public setutudentname(} studentname;} studentname;} studentname; toString(){return "sudent {[desutent:" + sustentid + "]、[sudineName:" + sustentName + "}";}}}それをもっと置くには、エンティティクラスのtoString()メソッドをオーバーライドし、それぞれ(またはキー属性)を印刷することが推奨されるアプローチです。次はconfig.xmlです。これには、基本的なJDBC構成が含まれています。
<?xml version = "1.0" encoding = "utf-8"?> <!doctype構成public " - // mybatis.org//dtd config 3.0 // en" "http://mybatis.org/dtd/mybatis-3-config.dtd" type = "org.xrq.domain.student"/> </typealiase> <環境デフォルト= "開発"> <環境id = "development"> <transactionManager Type = "JDBC"/> <DataSource Type = "Pooled"> <プロパティ名= "ドライバー" value = "com.mysql.jdbc.ddbc.driver"/>>>>>> value = "jdbc:mysql:// localhost:3306/test"/> <property name = "username" value = "root"/> <property name = "Password" value "/> </dataSource> </entument> </環境> <マッパー> <マッパーリソース=" desudent_mapper.xml "/>> </mappers> </mappers> </mappers>
次に、主に特定のsqlステートメントを習得する学生_mapper.xmlがあります。
<mapper namespace = "sudineMapper"> <resultMap = "sudents" id = "sustentmap"> <id column = "sudent_id" property = "sudentsid" jdbctype = "integer" /> <result column = "desudent_name" property = "desudentname" jdbctype = "" varchar " Student_id、Student_name from Student; </select> <挿入id = "insertsStudent" useGeneratedKeys = "true" keyproperty = "dusteent" parametertype = "sudints"> inserting into into intound(suduent_id、sudints_name)values(#{susteantid、jdbctype = integer} jdbctype = varchar}); </insert> </mapper> MyBatisutil.javaを作成します。これは、いくつかの基本的なMyBatis要素を作成するために使用されます。後続のクラスはこのクラスを継承します。
パブリッククラスmybatisutil {protected static sqlsessionfactory ssf; protected static reader reader; static {try {reader = resources.getResourceasReader( "config.xml"); ssf = new sqlsessionFactoryBuilder()。 sqlsession getSqlSession(){return ssf.opensession();}}エンタープライズレベルの開発要件:
1.個別の定義と実装
2。レイヤード開発、通常はdao-> service->コントローラー、特定の状況に応じて、もう1つのレイヤー/複数の層または1つのレイヤーが追加されることは除外されていません。
したがって、最初にStudentDao.javaインターフェイスを書きます:
public interface sustentdao {public list <Student> SelectAllStudents(); public int insertStudent(学生学生);}最後に、このインターフェイスを実装するためにStudentDaoimpl.javaを書きます。 mybatisutil.javaクラスを継承する必要があることに注意してください。
Public Class StudentDaoimpl拡張MyBatisutil ImplesiondStudentDao {private static final string namepace = "sustentmapper。"; public list <sudtent> selectalstudents(){sqlsession ss = getsqlsession(); list <sudtent> list = ss.selectlist(namespace + "chearthalt intect"; s.close ";学生){sqlsession ss = getsqlsession(); int i = ss.insert(namespace + "insertStudent"、sudent); // ss.commit(); ss.close(); return i;}}}テストクラスを書く:
Public Class StudentTest {public static void main(string [] args){studentdao entudentdao = new StudentDaoimpl(); desute desudent = new Student( "jack"); studentStudent(student.out.out.println( " + eatsis" Student.getStudentid()); system.out.println( "---- display sustent ------"); list <Student> StudentList = StudentDao.SelectAllStudents(); for(int i = 0、length = sustentlist.size(); i <length; i ++)system.out.println(sustentlist.get(i));}}}結果は空でなければなりません。
この例は、今日のコンテンツの紹介でもあると言っています。この理由は空いている理由は、挿入操作が行われたことですが、MyBatisは自動的に物事を提出するのに役立たないため、表示されるものは自然に空です。この場合、SQLSessionのCommit()メソッドを介してトランザクションを手動で送信する必要があります。つまり、StudentDaoimpl.javaクラスの17行目にコメントを開きます。
基本的なMyBatis挿入操作に加えて、この例には、挿入に基づいて挿入されたプライマリキーIDを返す機能もあります。
次に、Springを使用してMybatisのものを管理します。これは、エンタープライズレベルの開発で最も一般的に使用されるもの管理慣行でもあります。
春でmybatisのものを管理します
これを説明するための多くの記事がインターネット上にあり、私はたくさん検索しましたが、お互いをコピーして貼り付けるか、例全体を明確に説明しません。この部分を通して、私はMyBatisのものを管理するためにSpringを使用する方法を説明しようとします。
Springを使用してMybatisのものを管理し、Springの必要なモジュール豆、コンテキスト、コア、式、およびコモンズロギングに加えて、次のコンテンツも必要です。
(1)mybatis-spring-1.x.0.jar、これはスプリング統合mybatisに必要な瓶パッケージです。
(2)データベース接続プール、DBCP、C3P0を使用できます。私はここでアリババのドルイドを使用しています
(3)JDBC、TX、AOP、JDBCは基本的には言うまでもありません。 TXとAOPが使用されます。なぜなら、MyBatisの管理に対するSpringのサポートはAOPを通じて達成されるため
(4)aopalliance.jar、これはスプリングAOPを使用するために必要な瓶パッケージです
上記のJARパッケージは、Mavenを使用してダウンロードされます。 Mavenを使用していない人は、CSDNでダウンロードできます。あなたはそれを検索することができます。
MyBatisの構成ファイルconfig.xmlでは、JDBC接続を削除でき、TypeAliass部分のみを保持できます。
<?xml version = "1.0" encoding = "utf-8"?> <!doctype構成public " - // mybatis.org//dtd config 3.0 // en" "http://mybatis.org/dtd/mybatis-3-config.dtd" type = "org.xrq.domain.student"/> </typealiase> </configuration>
MyBatisの別の構成ファイルStudent_mapper.xmlを変更する必要がないことをお知らせください。次に、Spring構成ファイルを書き込み、spring.xmlに名前を付けます。
<?xmlバージョン= "1.0" encoding = "utf-8"?> <beans xmlns:xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns = "http://www.springframew ork.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"x MLNS:TX = "http://www.springframework.org/schema/tx" xmlns:aop = "http://www.springframework.org/schema/aop" xsi:schemalocation = "http://www.springframework http://www.springframework.org/schema/beans/spring-beans-4.2.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context-4.pring http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.2.2.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.2.xsd"><!<!---アノテーション構成 - > <TX:Annotation-driven-Manager = "TransactionManager"/>> <Context:Annotation-Con-contage:<contebont-scan-pack.データベース接続プール、AlibabaのDruidを使用 - > <bean id = "dataSource" init-method = "init" destroy-method = "close"> <property name = "url" value = "jdbc:mysql:// localhost:3306/test"/>> <プロパティname = "username"/> <"/> <propitial name"/> <"proprity name"/>> <"proprity name"/> id = "sqlsessionfactory"> <プロパティ名= "configlocation" value = "classpath:config.xml" /> <プロパティ名= "mapperlocations" value = "classpath:*_ mapper.xml" /> <プロパティ名= "datasource" ref = "datasource" />> < /bean> < name = "dataSource" ref = "dataSource"/> </bean> </beans>
これには、主にトランザクションマネージャーとデータベース接続プールが含まれます。
さらに、SQLSessionFactoryがあることがわかります。 Mybatisを使用した友人は、このクラスに精通している必要があります。 MyBatis環境の構成に使用されます。 sqlsessionFactoryには、2つの属性とmapperlocationsがあります。名前が示すように、構成ファイルの場所とマッピングファイルの場所を表します。ここで、パスが正しく構成されている限り、Springはこれら2つの構成ファイルを自動的にロードします。
変更したいのは、DAOの実装クラスです。現時点では、以前のMyBatisutilクラスを継承しなくなりましたが、mybatis-spring-1.x.0.jarからsqlsessiondaosupport.javaを継承します。特定のコードは次のとおりです。
@RepositoryPublic Class StudentDaoImpl拡張SQLSESSIONDAOSUPPORT IMPLEMENTS STUDENTDAO {PRIVATE STATIC STRING NAMESPACE = "StudentMapper。";@ResourcePublic void setSQLSessionFactory(SQLSessionFactory SQLSessionFactory){super.etsQLSessionFactory(sqlsessionfactory); selectalStudents(){return getSqlSession()。selectlist(namespace + "selectalStudents");} public intStudent(sudent sustent){return getsqlsession()。insert(namespace + "insertStudent"、sudent);}}}}ここでは2つの注釈が使用されています。それらについて個別に話しましょう。
(1)@Repository、このアノテーションは@Component、@Controller、および最も一般的な@Serviceアノテーションと同じです。これらはすべて、クラスをSpring Beanとして宣言できます。それらの違いは特定のセマンティクスではなく、注釈の位置にあります。前述のように、エンタープライズレベルのアプリケーションは階層開発の概念に焦点を当てているため、これらの4つの同様の注釈は次のように理解する必要があります。
•@Repositoryアノテーションは、データベースと直接対話するために使用されるDAOレイヤー、つまりDAOレイヤーに対応しています。一般的に言えば、メソッドは特定のSQLステートメントに対応します
•@Service Annotationは、サービスレイヤー、つまりサービスレイヤーに対応し、単一/複数のSQLステートメントを組み合わせる機能です。もちろん、それが単純な場合は、DAO層の方法を直接呼び出します。
•@コントローラーアノテーションは、コントロールレイヤー、つまりMVC設計モードのコントロールレイヤーに対応します。その機能は、ユーザー要求を受信し、異なるサービスを呼び出してリクエストに応じてデータを取得し、要件に応じてデータを組み合わせてフロントエンドに戻すことです。
•@コンポーネントアノテーション。これは、コンポーネントの概念に対応しています。 Beanがレイヤーに属していることを知らない場合は、@Component Annotationを使用して注釈を付けます。
これはまた、注釈の利点の1つを反映しています。名前を見て意味を知っていること、つまりこの注釈を見ると、このクラスの機能、つまりプロジェクト全体でのポジショニングを大まかに知っています。
(2)@Resource、この注釈と@Autowiredアノテーションは同じ意味を持ち、両方を属性属性で自動的に注入できます。 SQLSessionFactoryはMyBatisの中核であるため、Spring.xmlで宣言されています。したがって、ID「SQLSessionFactory」を備えたBeanは、@Resourceアノテーションを通じてここに注入されます。その後、SQLSessionはgetSqlSession()メソッドを介して取得でき、データは追加、削除、変更、およびチェックされます。
最後に、テストするテストクラスを書くことにすぎません。
Public Class StudentTest {public static void main(string [] args){applicationContext ac = new classpathxmlapplicationcontext( "spring.xml"); sustentdao sustentdao =(desuteddao)ac.getbean( "sustentdaoimpl"); desudent sudent = new sudent(); studentname "); StudentDao.insertStudent(sudent); system.out.println( "j =" + j + "/n"; system.out.println("---- Display学生------"); list <Student> Studentlist = sustentDao.SelectallStudents(); for(int i = 0、length = sustentlist.size(); i <length; i ++)system.out.println(sustentlist.get(i));}}} StudentDaoimpl.javaクラスは@Repositoryアノテーションを使用しており、エイリアスを指定していないため、SpringコンテナのStudentDaoimpl.javaの名前は「最初の文字小文字 +残りの文字」、つまり「StudentDaoimpl」です。
プログラムを実行した後、新しい学生がコンソールで横断されたこと、つまり、学生がデータベースに直接挿入されたことがわかります。プロセス全体にコミットやロールバックはありませんでした。それらはすべて春までに実装されました。これは、Springを使用してMybatisで物事を管理することです。
ポストスクリプト
この記事では、MyBatisの基本的な使用をレビューし、Springを使用してMyBatisで物事を管理し、より詳細なコードの例を示します。困っている友人は、コードに従ってそれを研究することができます。この記事に基づいて、後で記事を書き、単一のテーブルと複数のテーブル間のMulti-Dataのもの管理の実装を説明します。この要件は、企業やアプリケーションの一般的な要件でもあります。