熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java開源技術 >> 正文

基於Spring+Ibatis的安全線程實現

2022-06-13   來源: Java開源技術 

  過去做過一些基於springhibernate整合應用的實例本人感覺spring與hibernate最好的結合就是泛型Dao的實現代碼量節省了一半而且業務邏輯一目了然

  後來做別的系統時候考慮過這樣的框架但是數據庫結構如果不固定動態生成的東西比較多這個時候只好放棄了hibernate而選擇了同樣具有orm性能的ibatis下面就spring與ibatis的結合相關配置做下說明(如有不同意見希望交流)

  首先spring和ibatis具體下載和安裝就不多說了直接切入正題

  Spring框架下的ibatis應用特別是在容器事務管理模式下的ibatis應用開發

  部署如下

  首先spring配置文件

  Spring_basexml

  <?xml version= encoding=UTF ?>

  <!DOCTYPE beans PUBLIC //SPRING//DTD BEAN//EN beansdtd>

  <beans defaultlazyinit=true>

  <! 配置數據源 >

  <bean id=dataSource class=monsdbcpBasicDataSource destroymethod=close>

  <property name=driverClassName>

  <value>netsourceforgejtdsjdbcDriver</value>

  </property>

  <property name=url>

  <value>jdbc:jtds:sqlserver://localhost:/test</value>

  </property>

  <property name=username>

  <value>sa</value>

  </property>

  <property name=password>

  <value>sa</value>

  </property>

  <property name=maxActive>

  <value></value>

  </property>

  <property name=maxIdle>

  <value></value>

  </property>

  <property name=maxWait>

  <value></value>

  </property>

  </bean>

  /////////////////// dataSource配置你的數據源連接

  <bean id=sqlMapClient

  class=orgspringframeworkormibatisSqlMapClientFactoryBean>

  <property name=configLocation>

  <value>SqlMap_configxml</value>

  </property>

  <property name=dataSource><! 從指定dataSource中獲取數據源 亦可把該定義放到每個自定義Dao中>

  <ref bean=dataSource />

  </property>

  </bean>

  //////////////////// sqlMapClient集成ibatis配置文件和把數據源與ibatis相關聯

  <! 配置事務管理 >

  <bean id=transactionManager class=orgspringframeworkjdbcdatasourceDataSourceTransactionManager>

  <property name=dataSource>

  <ref local=dataSource />

  </property>

  </bean>

  ///////////////// transactionManager:配置事務管理

  <!公共組件>

  <import resource=spring_otherxml />

  ////////////把用戶自定義Bean與基本bean分開集成進去spring_otherxml文件

  </beans>

  以上是spring 把一些ibatis相關配置集成到自己的配置文件裡面

  Spring_otherxml

  <?xml version= encoding=UTF?>

  <!DOCTYPE beans PUBLIC //SPRING//DTD BEAN//EN beansdtd>

  <beans>

  <bean id=userService class=comuserUserServiceImpl>

  <property name=transactionManager>

  <ref bean=transactionManager />

  </property>

  <property name=userDao>

  <ref local=userDao />

  </property>

  </bean>

  ////////////////////////使用service管理所有用戶自定義bean和Dao操作用來設置事務回滾線程安全等

  <bean id=userDao class=comuserdaoUserDaoImpl>

  <property name=sqlMapClient ref=sqlMapClient/>

  </bean>

  ///////////////用戶自定義Dao操作因spring_basexml中sqlMapClient已經把dataSource包含故dataSource不再聲明如果該操作需要別的數據連接可加入例如

  ////////<property name=dataSource ref=dataSource/>//////////

  </beans>

  Spring_otherxml存放用戶自定義bean

  SqlMap_configxml

  <?xml version= encoding=UTF ?>

  <!DOCTYPE sqlMapConfig

  PUBLIC ////DTD SQL Map Config //EN

  mapconfigdtd>

  <sqlMapConfig>

  <settings lazyLoadingEnabled=true

  useStatementNamespaces=true

  enhancementEnabled=true

  errorTracingEnabled=true

  />

  /////////////定義ibatis相關操作參數例如延遲加載命名空間是否生效是否打開緩存調試階段出錯信息反饋等等

  <sqlMap resource=com/user/userxml />

  //////////////包含用戶的相關操作xml文件

  </sqlMapConfig>

  Userxml

  <?xml version= encoding=UTF ?>

  <!DOCTYPE sqlMap

  PUBLIC ////DTD SQL Map //EN

  mapdtd>

  <sqlMap namespace=User>

  <typeAlias alias=user type=comuserUser /><! obj >

  <!  get user >

  <select id=getUser

  parameterClass=javalangString

  resultClass=user>

  <![CDATA[

  select

  id

  name

  sex

  from

  t_user

  where name like #name#

  ]]>

  </select>

  <! update user >

  <update id=updateUser parameterClass=user>

  <![CDATA[

  update t_user

  set

  name=#name#

  sex=#sex#

  where id = #id#

  ]]>

  </update>

  <insert id=insertUser parameterClass=user>

  <![CDATA[

  insert into t_user(

  id

  name

  sex)

  values(

  #id#

  #name#

  #sex#

  )

  ]]>

  </insert>

  <delete id=deleteUser parameterClass=javalangString>

  <![CDATA[

  delete from t_user

  where id = #value#

  ]]>

  </delete>

  <select id=selectUser  resultClass=user>

  <![CDATA[

  select * from t_user order by id desc

  ]]>

  </select>

  </sqlMap>

  該配置文件屬性就不多了用戶可在網上搜一堆夠看了

  針對spring_otherxml 裡面的用戶自定義bean如下

  UserDaojava 接口

  package comuserdao;

  import javautilList;

  import comuserUser;      

  public interface UserDao {

  public User getUser(String name);

  public void updateUser(User user);

  public List selectUser();

  public void insertUser(User user);

  }

  UserDaoImpljava 實現類

  package comuserdao;   

  import javautilList;   

  import orgspringframeworkormibatissupportSqlMapClientDaoSupport;   

  import comuserUser;       

  public class UserDaoImpl extends SqlMapClientDaoSupport implements UserDao {

  //private static Logger log = LoggergetLogger(UserDaoImplclass);

  public User getUser(String name) {

  return (User) thisgetSqlMapClientTemplate()queryForObject(UsergetUsername);

  }   

  public void updateUser(User user) {

  thisgetSqlMapClientTemplate()update(UserupdateUser user);

  }   

  public List selectUser() {

  return thisgetSqlMapClientTemplate()queryForList(UserselectUser);

  }

  public void insertUser(User user) {

  thisgetSqlMapClientTemplate()insert(UserinsertUser user);

  }

  }

  現在大家也許看到這裡覺得就差不多了該Dao方法差不多全了可以進行操作了其實不然下面我載自官方的一段

  Spring提供兩種方式的編程式事務管理分別是使用TransactionTemplate和直接使用PlatformTransactionManager
  ⅰ TransactionTempale采用和其他Spring模板如JdbcTempalte和HibernateTemplate一樣的方法它使用回調方法把應用程序從處理取得和釋放資源中解脫出來如同其他模板TransactionTemplate是線程安全的

  所以我們下面我們要再封裝一層以實現線程是安全的這就是我們在spirng_otherxml裡面的那段配置實現

  baseServicejava

  package combase;

  import orgspringframeworktransactionsupportTransactionTemplate;

  /**

  * 工廠的基礎類.

  * @author 劉玉華

  * @time

  */

  public class BaseService extends TransactionTemplate{

  private static final long serialVersionUID = L;

  }

  serviceFactoryjava

  package combase;   

  import orgspringframeworkbeansfactoryBeanFactory;

  import orgntextsupportClassPathXmlApplicationContext;   

  import comuserdaoUserDao;   

  /**

  * 數據操作工廠所有的數據操作都從該工廠中獲得

  * @author 劉玉華

  * @time

  */   

  public class ServiceFactory {

  private static BeanFactory factory = null;   

  static {

  ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(

  new String[] {spring_basexml});

  factory = (BeanFactory) context;

  }       

  /**

  * 獲得用戶服務類

  * @return 用戶服務

  */

  public static UserDao getUserService(){

  return (UserDao) factorygetBean(userService);

  }

  }

  我們所需要做的就是繼承Baseservicejava 以實現tx管理

  UserServicejava

  package comuser;

  import javautilList;

  public interface UserService {

  public User getUser(final String name);

  public void updateUser(final User user);

  public List selectUser();

  public void insertUser(final User user);

  }

  UserServiceImpljava 用戶服務實現類

  package comuser;   

  import javautilList;   

  import orgspringframeworktransactionTransactionStatus;

  import orgspringframeworktransactionsupportTransactionCallback;

  import combaseBaseService;

  import comuserdaoUserDao;

  public class UserServiceImpl extends BaseService implements UserDao {

  private UserDao userDao;

  public UserDao getUserDao() {

  return userDao;

  }

  public void setUserDao(UserDao userDao) {

  thisuserDao = userDao;

  }

  public List selectUser() {

  Object obj = execute(new TransactionCallback(){

  public Object doInTransaction(TransactionStatus status) {

  return userDaoselectUser();

  }

  });

  return (List)obj;

  }

  public User getUser(final String name){

  Object obj = execute(new TransactionCallback(){

  public Object doInTransaction(TransactionStatus status) {

  // TODO Autogenerated method stub

  return userDaogetUser(name);

  }

  });

  return (User) obj;

  }

  public void insertUser(final User user) {

  Object obj = execute(new TransactionCallback(){

  public Object doInTransaction(TransactionStatus status) {

  userDaoinsertUser(user);

  return null;

  }

  });

  }

  public void updateUser(final User user) {

  Object obj = execute(new TransactionCallback(){

  public Object doInTransaction(TransactionStatus arg) {

  userDaoupdateUser(user);

  return null;

  }

  });

  

  }   

  }
    這樣我們就把相關操作實現事務控制了

  數據表建立

  create table t_user(

  id int null

  name varchar() null

  sex int null

  )

  這樣我們在以後調用方式為

  測試類

  package comuserjunit;   

  import javautilList;   

  import combaseServiceFactory;

  import comuserUser;

  import comuserdaoUserDao;

  import commonLogger;

  public class UserTest {

  private static Logger log = LoggergetLogger(UserTestclass);

  public static void main(String args[]){

  UserDao service = ServiceFactorygetUserService();

  User user=null;

  int i = ;

  switch (i) {

  case :

  usersetId();

  usersetName();

  usersetSex();

  serviceupdateUser(user);

  Systemoutprintln(usergetName()+ +usergetSex());

  break;

  case :

  try {

  user = servicegetUser();

  } catch (Exception e) {

  logdebug(出錯了+egetMessage());

  }

  Systemoutprintln(usergetId());

  case :

  List<User> ls = serviceselectUser();

  for (int j = ; j < lssize(); j++) {

  Systemoutprintln(lsget(j)getId()+====+lsget(j)getName());

  }

  case :

  List<User> ls = serviceselectUser();

  for (int j = ; j < lssize(); j++) {

  user = lsget(j);

  Systemoutprintln(usergetId()+usergetName()+usergetSex()+usergetAddress());

  }

  for (int j = ; j < ; j++) {

  usersetId(usergetId()+);

  serviceinsertUser(user);

  }

  default:

  break;

  }

  }

  }


From:http://tw.wingwit.com/Article/program/Java/ky/201311/28732.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.