问:
Spring boot 1.5 tests don't roll back transaction
I'm starting a simple Spring boot project + JPA + Hibernate + Mysql. Before starting coding I created some very simple tests but unfortunately the behaiour is not that expected. This is my test class:

```<code> @RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(locations = "classpath:test.properties")
@Transactional
public class TenantTest {

    @Autowired
    private TenantRepository tenantRepository;

    @Test
    public void createTenant() {
        Tenant tenant = new Tenant();
        tenant.setAddress("Street n.1");
        tenant.setAlias("tenant");
        tenant.setCity("Milan");
        tenant.setCountry("Italy");
        tenant.setEmail("info@email.com");
        tenant.setLandlinePhone("3902123456");
        tenant.setMobilePhone("39347123456");
        tenant.setName("Tenant 1");
        tenant.setType(TenantType.RESELLER);

        Tenant savedObj = tenantRepository.save(tenant);

        assertNotNull("Tenant null after save!", savedObj);

    }

    @Test
    public void createTenantWithInvalidEmail() {
        Tenant tenant = new Tenant();
        tenant.setAddress("Street n.1");
        tenant.setAlias("tenant");
        tenant.setCity("Milan");
        tenant.setCountry("Italy");
        tenant.setEmail("info@email");
        tenant.setLandlinePhone("3902123456");
        tenant.setMobilePhone("39347123456");
        tenant.setName("Tenant 1");
        tenant.setType(TenantType.RESELLER);

        Tenant savedObj = tenantRepository.save(tenant);

        assertNotNull("Tenant null after save!", savedObj);

    }
</code>```

According to Spring documentation (https://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testing-tx), each test should be rolled back. Instead in my example this doens't happen. In fact I've this error for the second test:

```<code>    org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [UK_6xsyaq3xonk8dkjed1lmu31ve]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:278)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:488)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy130.save(Unknown Source)
    at com.test.server.TenantTest.createTenantWithInvalidEmail(TenantTest.java:59)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2909)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3480)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:626)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:280)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:261)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:306)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
    at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:67)
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:780)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:765)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
    at com.sun.proxy.$Proxy124.persist(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:508)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:504)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:489)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    ... 39 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'tenant' for key 'UK_6xsyaq3xonk8dkjed1lmu31ve'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
    at com.mysql.jdbc.Util.getInstance(Util.java:408)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:935)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2501)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
    at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
    at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
    at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114)
    at com.sun.proxy.$Proxy82.executeUpdate(Unknown Source)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:205)
    ... 80 more
</code>```

This happens obviously because the transaction is not rolled back. I also printed debug log of spring and Spring is saying it is rolling back the transaction:

```<code> 017-06-06 18:29:12.683  INFO 7556 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@3f200884 testClass = TenantTest, testInstance = com.test.server.TenantTest@35fac3ba, testMethod = createTenant@TenantTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4d339552 testClass = TenantTest, locations = '{}', classes = '{class com.test.server.TestApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@5025a98f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@192b07fd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@520a3426], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@7d43f1c9]; rollback [true]
2017-06-06 18:29:12.753  INFO 7556 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test context [DefaultTestContext@3f200884 testClass = TenantTest, testInstance = com.test.server.TenantTest@35fac3ba, testMethod = createTenant@TenantTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4d339552 testClass = TenantTest, locations = '{}', classes = '{class com.test.server.TestApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@5025a98f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@192b07fd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@520a3426], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].
2017-06-06 18:29:12.756  INFO 7556 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@3f200884 testClass = TenantTest, testInstance = com.test.server.TenantTest@4c599679, testMethod = createTenantWithDuplicatedAlias@TenantTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4d339552 testClass = TenantTest, locations = '{}', classes = '{class com.test.server.TestApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@5025a98f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@192b07fd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@520a3426], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@7d43f1c9]; rollback [true]
2017-06-06 18:29:12.760  WARN 7556 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1062, SQLState: 23000
2017-06-06 18:29:12.760 ERROR 7556 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : Duplicate entry 'tenant' for key 'UK_6xsyaq3xonk8dkjed1lmu31ve'
2017-06-06 18:29:12.764  INFO 7556 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test context [DefaultTestContext@3f200884 testClass = TenantTest, testInstance = com.test.server.TenantTest@4c599679, testMethod = createTenantWithDuplicatedAlias@TenantTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4d339552 testClass = TenantTest, locations = '{}', classes = '{class com.test.server.TestApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@5025a98f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@192b07fd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@520a3426], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].
</code>```

Relevant part of my properties configuration:

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto: create-drop
spring.jpa.hibernate.naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.database: mysql
spring.jpa.show-sql: false
spring.jpa.properties.hibernate.max_fetch_depth=3
spring.jpa.properties.hibernate.jdbc.fetch_size=150
spring.jpa.properties.hibernate.jdbc.batch_size=100
spring.jpa.properties.hibernate.cache.use_second_level_cache=true
</code>```

I'm using the annotation @Transaction at level class. I don't see what is wrong with this configuration. Do you have some advice?

答:
When using MySQL version < 5.5.5 then the default storage engine is MyISAM which doesn't support transactions (or the default-storage-engine property in the my.cfg is set to MyISAM).

The storage engine that does support transactions is InnoDB.

Now you basically have 2 ways of solving this.

Upgrade MySQL to at least 5.5.5 (or even more recent)

Use the proper Hibernate Dialect

To specify the proper dialect you need to set the spring.jpa.database-platform to the correct class.

```<code>spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
</code>```

Setting this dialect will enforce the storage engine InnoDB.

NOTE: You should set either spring.jpa.database-platform or spring.jpa.databse but not both (as the latter will override the dialect!).

If you are using Hibernate 5.2.8 or up you can omit the spring.jpa.database-platform and only set the spring.jpa.database (or let it auto-detect) and set the hibernate.dialect.storage_engine property to innodb. (See also this blog on that).

```<code>spring.jpa.database=MYSQL
spring.jpa.properties.hibernate.dialect.storage_engine=innodb
</code>```

Body:
I'm starting a simple Spring boot project + JPA + Hibernate + Mysql. Before starting coding I created some very simple tests but unfortunately the behaiour is not that expected. This is my test class:

 @RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(locations = "classpath:test.properties")
@Transactional
public class TenantTest {

    @Autowired
    private TenantRepository tenantRepository;

    @Test
    public void createTenant() {
        Tenant tenant = new Tenant();
        tenant.setAddress("Street n.1");
        tenant.setAlias("tenant");
        tenant.setCity("Milan");
        tenant.setCountry("Italy");
        tenant.setEmail("info@email.com");
        tenant.setLandlinePhone("3902123456");
        tenant.setMobilePhone("39347123456");
        tenant.setName("Tenant 1");
        tenant.setType(TenantType.RESELLER);

        Tenant savedObj = tenantRepository.save(tenant);

        assertNotNull("Tenant null after save!", savedObj);

    }

    @Test
    public void createTenantWithInvalidEmail() {
        Tenant tenant = new Tenant();
        tenant.setAddress("Street n.1");
        tenant.setAlias("tenant");
        tenant.setCity("Milan");
        tenant.setCountry("Italy");
        tenant.setEmail("info@email");
        tenant.setLandlinePhone("3902123456");
        tenant.setMobilePhone("39347123456");
        tenant.setName("Tenant 1");
        tenant.setType(TenantType.RESELLER);

        Tenant savedObj = tenantRepository.save(tenant);

        assertNotNull("Tenant null after save!", savedObj);

    }

According to Spring documentation (https://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testing-tx), each test should be rolled back. Instead in my example this doens't happen. In fact I've this error for the second test:

    org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [UK_6xsyaq3xonk8dkjed1lmu31ve]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:278)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:488)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy130.save(Unknown Source)
    at com.test.server.TenantTest.createTenantWithInvalidEmail(TenantTest.java:59)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2909)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3480)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:626)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:280)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:261)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:306)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
    at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:67)
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:780)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:765)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
    at com.sun.proxy.$Proxy124.persist(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:508)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:504)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:489)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    ... 39 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'tenant' for key 'UK_6xsyaq3xonk8dkjed1lmu31ve'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
    at com.mysql.jdbc.Util.getInstance(Util.java:408)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:935)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2501)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
    at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
    at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
    at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114)
    at com.sun.proxy.$Proxy82.executeUpdate(Unknown Source)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:205)
    ... 80 more

This happens obviously because the transaction is not rolled back. I also printed debug log of spring and Spring is saying it is rolling back the transaction:

 017-06-06 18:29:12.683  INFO 7556 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@3f200884 testClass = TenantTest, testInstance = com.test.server.TenantTest@35fac3ba, testMethod = createTenant@TenantTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4d339552 testClass = TenantTest, locations = '{}', classes = '{class com.test.server.TestApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@5025a98f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@192b07fd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@520a3426], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@7d43f1c9]; rollback [true]
2017-06-06 18:29:12.753  INFO 7556 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test context [DefaultTestContext@3f200884 testClass = TenantTest, testInstance = com.test.server.TenantTest@35fac3ba, testMethod = createTenant@TenantTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4d339552 testClass = TenantTest, locations = '{}', classes = '{class com.test.server.TestApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@5025a98f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@192b07fd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@520a3426], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].
2017-06-06 18:29:12.756  INFO 7556 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@3f200884 testClass = TenantTest, testInstance = com.test.server.TenantTest@4c599679, testMethod = createTenantWithDuplicatedAlias@TenantTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4d339552 testClass = TenantTest, locations = '{}', classes = '{class com.test.server.TestApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@5025a98f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@192b07fd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@520a3426], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@7d43f1c9]; rollback [true]
2017-06-06 18:29:12.760  WARN 7556 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1062, SQLState: 23000
2017-06-06 18:29:12.760 ERROR 7556 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : Duplicate entry 'tenant' for key 'UK_6xsyaq3xonk8dkjed1lmu31ve'
2017-06-06 18:29:12.764  INFO 7556 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test context [DefaultTestContext@3f200884 testClass = TenantTest, testInstance = com.test.server.TenantTest@4c599679, testMethod = createTenantWithDuplicatedAlias@TenantTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4d339552 testClass = TenantTest, locations = '{}', classes = '{class com.test.server.TestApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@5025a98f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@192b07fd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@520a3426], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].

Relevant part of my properties configuration:

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto: create-drop
spring.jpa.hibernate.naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.database: mysql
spring.jpa.show-sql: false
spring.jpa.properties.hibernate.max_fetch_depth=3
spring.jpa.properties.hibernate.jdbc.fetch_size=150
spring.jpa.properties.hibernate.jdbc.batch_size=100
spring.jpa.properties.hibernate.cache.use_second_level_cache=true

I'm using the annotation @Transaction at level class. I don't see what is wrong with this configuration. Do you have some advice?

Body:
When using MySQL version < 5.5.5 then the default storage engine is MyISAM which doesn't support transactions (or the default-storage-engine property in the my.cfg is set to MyISAM).

The storage engine that does support transactions is InnoDB.

Now you basically have 2 ways of solving this.

Upgrade MySQL to at least 5.5.5 (or even more recent)

Use the proper Hibernate Dialect

To specify the proper dialect you need to set the spring.jpa.database-platform to the correct class.

spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

Setting this dialect will enforce the storage engine InnoDB.

NOTE: You should set either spring.jpa.database-platform or spring.jpa.databse but not both (as the latter will override the dialect!).

If you are using Hibernate 5.2.8 or up you can omit the spring.jpa.database-platform and only set the spring.jpa.database (or let it auto-detect) and set the hibernate.dialect.storage_engine property to innodb. (See also this blog on that).

spring.jpa.database=MYSQL
spring.jpa.properties.hibernate.dialect.storage_engine=innodb


来源: stackexchange

问:
sqoop import from mysql to hive, username getting changed (Access Denied for user)
I am trying to import some data from mysql to hive via sqoop. It works when both sqoop and mysql db are on the same host, otherwise it fails. This is the query I am executing.

```<code>[user@xyz ~]$ sqoop import --connect "jdbc:mysql://abc.something.com/test" --username user --password pass --table dataSql --hive-import --hive-table test.dataHive --target-dir /tmp/sqoop$RANDOM
</code>```

Please note that I am currently on host xyz and I am trying to connect to a mysql db on host abc. Following are the error I see.

```<code>ERROR: org.apache.sqoop.manager.SqlManager - Error executing statement: java.sql.SQLException: Access denied for user 'user'@'xyz.something.com' (using password: YES)
.
.
.
ERROR: org.apache.sqoop.manager.CatalogQueryManager - Failed to list columns java.sql.SQLException: Access denied for user 'user'@'xyz.something.com' (using password: YES)
.
.
.
</code>```

and so on. My question is, why is my machine appending its hostname to username ('user'@'xyz.something.com')? How do I solve it?

答: The --username user --password pass here specifies the user credentials given access to use the test database, it is not for the mysql as a whole. So modify this accordingly.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to import some data from mysql to hive via sqoop. It works when both sqoop and mysql db are on the same host, otherwise it fails. This is the query I am executing.

[user@xyz ~]$ sqoop import --connect "jdbc:mysql://abc.something.com/test" --username user --password pass --table dataSql --hive-import --hive-table test.dataHive --target-dir /tmp/sqoop$RANDOM

Please note that I am currently on host xyz and I am trying to connect to a mysql db on host abc. Following are the error I see.

ERROR: org.apache.sqoop.manager.SqlManager - Error executing statement: java.sql.SQLException: Access denied for user 'user'@'xyz.something.com' (using password: YES)
.
.
.
ERROR: org.apache.sqoop.manager.CatalogQueryManager - Failed to list columns java.sql.SQLException: Access denied for user 'user'@'xyz.something.com' (using password: YES)
.
.
.

and so on. My question is, why is my machine appending its hostname to username ('user'@'xyz.something.com')? How do I solve it?


问:
Static members need special synchronization blocks?
I have a class which looks something like this:

```<code>public class Test {

private static final Object someObject = new Object();

public void doSomething()
{
    synchronized (someObject) {
        System.out.println(someObject.toString());
    }
}

}
</code>```

Can I consider the object to be synchronized, or is there a problem since it is a static member?

Edit: note that different threads might be accessing doSomething() and the object must be accessed in a thread-safe manner in that case.

答: What happens if Test class is loaded using different classloaders? </p>

OwnerDisplayName: Yuval A

ContentLicense: CC BY-SA 2.5

Body:
I have a class which looks something like this:

public class Test {

private static final Object someObject = new Object();

public void doSomething()
{
    synchronized (someObject) {
        System.out.println(someObject.toString());
    }
}

}

Can I consider the object to be synchronized, or is there a problem since it is a static member?

Edit: note that different threads might be accessing doSomething() and the object must be accessed in a thread-safe manner in that case.

LastEditorDisplayName: Yuval A


问:
VBA auto hide ribbon in Excel 2013
How to Auto-hide Ribbon in Excel 2013 in VBA? I would like to achieve exactly what I get by clicking on the upper arrow icon at the right top of Excel menu marked with blue in the picture below and then clicking on the first option marked with orange:

I would be also interested in VBA switching back to the third option Show Tabs and Commands. Important thing for me is to keep in the Excel menu the upper arrow icon (marked with blue).

I have tried hints shown in this thread: VBA minimize ribbon in Excel
but I am not satisfied with results.

Attempt 1

```<code>Application.ExecuteExcel4Macro "Show.ToolBar(""Ribbon"",False)
</code>```

This is good but hides the blue icon.

Attempt 2

```<code>CommandBars.ExecuteMso "MinimizeRibbon"
</code>```

This is close to what I want. This keeps the blue icon but does not hide the entire menu. It switches to the second option displayed in the picture Show Tabs.

Attempt 3

```<code>SendKeys "^{F1}"
</code>```

The attampt does not work at all. Moreover, it is supposed to imitate the attempt 2. So even that would not satisfy me.

答:
I call this macro on Workbook_Open to check for the ribbon and if not hidden, it will hide the ribbon (I actually have it located in another Sub that also removes the formula bar, status bar, headings, and gridlines at Workbook_Open)...

```<code>Sub HideRibbon()
If CommandBars("Ribbon").Controls(1).Height < 100 Then
Exit Sub
Else
    CommandBars.ExecuteMso ("MinimizeRibbon")
End If
End Sub
</code>```

Then I call this macro on Workbook_BeforeClose to check for the ribbon and if it is not shown, it will show the ribbon for the next excel spreadsheet that is opened.

```<code>Sub ShowRibbon()
If CommandBars("Ribbon").Controls(1).Height > 100 Then
Exit Sub
Else
    CommandBars.ExecuteMso ("MinimizeRibbon")
End If
End Sub
</code>```

This eliminates the chance of hiding the ribbon when the workbook is opened and a user then manually showing the ribbon which in turn would reverse the show on close and actually hide the ribbon. On open, the ribbon would then be shown again. This will keep it the same every time on open and close of the workbook.

Title: VBA auto hide ribbon in Excel 2013

Body:
How to Auto-hide Ribbon in Excel 2013 in VBA? I would like to achieve exactly what I get by clicking on the upper arrow icon at the right top of Excel menu marked with blue in the picture below and then clicking on the first option marked with orange:

I would be also interested in VBA switching back to the third option Show Tabs and Commands. Important thing for me is to keep in the Excel menu the upper arrow icon (marked with blue).

I have tried hints shown in this thread: VBA minimize ribbon in Excel
but I am not satisfied with results.

Attempt 1

Application.ExecuteExcel4Macro "Show.ToolBar(""Ribbon"",False)

This is good but hides the blue icon.

Attempt 2

CommandBars.ExecuteMso "MinimizeRibbon"

This is close to what I want. This keeps the blue icon but does not hide the entire menu. It switches to the second option displayed in the picture Show Tabs.

Attempt 3

SendKeys "^{F1}"

The attampt does not work at all. Moreover, it is supposed to imitate the attempt 2. So even that would not satisfy me.

Body:
I call this macro on Workbook_Open to check for the ribbon and if not hidden, it will hide the ribbon (I actually have it located in another Sub that also removes the formula bar, status bar, headings, and gridlines at Workbook_Open)...

Sub HideRibbon()
If CommandBars("Ribbon").Controls(1).Height < 100 Then
Exit Sub
Else
    CommandBars.ExecuteMso ("MinimizeRibbon")
End If
End Sub

Then I call this macro on Workbook_BeforeClose to check for the ribbon and if it is not shown, it will show the ribbon for the next excel spreadsheet that is opened.

Sub ShowRibbon()
If CommandBars("Ribbon").Controls(1).Height > 100 Then
Exit Sub
Else
    CommandBars.ExecuteMso ("MinimizeRibbon")
End If
End Sub

This eliminates the chance of hiding the ribbon when the workbook is opened and a user then manually showing the ribbon which in turn would reverse the show on close and actually hide the ribbon. On open, the ribbon would then be shown again. This will keep it the same every time on open and close of the workbook.


问:
How to set logback.xml file path in yaml file of springboot
We can set the logback.xml file path using the environment variable -Dlogging.config=file:///path/to/file.
How can I set above property in the yaml config file of springboot ?</p>

答:
As stated in the documentation, you can use
logging.config: classpath:path/to/file in application.yaml


问:
sql request with Count
I have this data base. Created 3 tables.

I need to query the database to extract the titles in which more than three authors.

I tried different ways, but I can not count the number of books written by three or more authors. How can I calculate how many echoes wrote the book in my table?

```<code> CREATE TABLE `authors` (
      `id` int(11) NOT NULL,
      `name` text CHARACTER SET utf8 NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `authors` (`id`, `name`) VALUES
(1, 'Orwell'),
(2, 'Balsak'),
(3, 'Gugo');

-- --------------------------------------------------------

CREATE TABLE `books` (
  `id` int(11) NOT NULL,
  `title` text CHARACTER SET utf8 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `books` (`id`, `title`) VALUES
(1, '1984'),
(2, 'crime and punishment'),
(3, 'Hunger games');

-- --------------------------------------------------------

CREATE TABLE `books_authos` (
  `author_id` int(11) DEFAULT NULL,
  `book_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `books_authos` (`author_id`, `book_id`) VALUES
(1, 1),
(1, 3),
(1, 2),
(3, 2),
(2, 2);
</code>```

答:
Below mentioned query will help you to extract title of book written by more than 3 authors.

```<code>SELECT b.title AS titles FROM books b
INNER JOIN books_authos ba ON ba.book_id = b.id
GROUP BY ba.book_id
HAVING COUNT(DISTINCT(ba.author_id)) >= 3
</code>```

Let me know if you need other specific output.

Title: sql request with Count

Body:
I have this data base. Created 3 tables.

I need to query the database to extract the titles in which more than three authors.

I tried different ways, but I can not count the number of books written by three or more authors. How can I calculate how many echoes wrote the book in my table?

 CREATE TABLE `authors` (
      `id` int(11) NOT NULL,
      `name` text CHARACTER SET utf8 NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `authors` (`id`, `name`) VALUES
(1, 'Orwell'),
(2, 'Balsak'),
(3, 'Gugo');

-- --------------------------------------------------------

CREATE TABLE `books` (
  `id` int(11) NOT NULL,
  `title` text CHARACTER SET utf8 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `books` (`id`, `title`) VALUES
(1, '1984'),
(2, 'crime and punishment'),
(3, 'Hunger games');

-- --------------------------------------------------------

CREATE TABLE `books_authos` (
  `author_id` int(11) DEFAULT NULL,
  `book_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `books_authos` (`author_id`, `book_id`) VALUES
(1, 1),
(1, 3),
(1, 2),
(3, 2),
(2, 2);

Body:
Below mentioned query will help you to extract title of book written by more than 3 authors.

SELECT b.title AS titles FROM books b
INNER JOIN books_authos ba ON ba.book_id = b.id
GROUP BY ba.book_id
HAVING COUNT(DISTINCT(ba.author_id)) >= 3

Let me know if you need other specific output.


问:
Could Not Resolve Dependencies for AndroidSweetSheet library
So I am back working on my Android app after a few months and after having familiarized myself with the code again, I notice that my AndroidSweetSheet library has become somewhat deprecated since the compiler is failing to resolve the dependency. This is strange considering the fact that all used to work and was honkey dorey.

What could be the issue because when I navigate to:

https://repo.jfrog.org/artifactory/libs-release-bintray/com/github/zzz40500/AndroidSweetSheet/221317862b/AndroidSweetSheet-221317862b.jar?referrer

I get an http 404 stating that the resource I have just requested could not be found:

```<code>{
  "errors" : [ {
    "status" : 404,
    "message" : "Could not find resource"
  } ]
}
</code>```

答:
All I needed to do was:

1. Update my Android Support Repository

2. Update my buildToolsVersion from '23.0.0' to '25.0.0' (the latest). I left my compileSdkVersion at 23. Synced Gradle files and that resolved the issue.

Body:
So I am back working on my Android app after a few months and after having familiarized myself with the code again, I notice that my AndroidSweetSheet library has become somewhat deprecated since the compiler is failing to resolve the dependency. This is strange considering the fact that all used to work and was honkey dorey.

What could be the issue because when I navigate to:

https://repo.jfrog.org/artifactory/libs-release-bintray/com/github/zzz40500/AndroidSweetSheet/221317862b/AndroidSweetSheet-221317862b.jar?referrer

I get an http 404 stating that the resource I have just requested could not be found:

{
  "errors" : [ {
    "status" : 404,
    "message" : "Could not find resource"
  } ]
}


问:
Convert & sort javascript array numerically using non-numeric key
I have a JS array in following structure:

```<code>Array(
    [0] => Array(
        reference : "8926"
        name : "xyz1"
        id_product : "78"
    )
    [1] => Array(
        reference : "11588"
        name : "xyz2"
        id_product : "21"
    )
    [2] => Array(
        reference : "119"
        name : "xyz3"
        id_product : "135"
    )
)
</code>```

I needed to sort this array using the reference key, I have done it using multisort function;

But the problem is : even though reference is numeric but in the array structure it is defined as string and hence instead of sorting like:
119, 8926, 11588 it is sorting it like 11588 119 8926, i.e., like string.

I cannot re-structure the array because I receive it through an API, is there anyway to sort it numerically without having to recreate it in numeric data type separately (because I have to pass the array forward in same format & hence double-conversion will make the script hectic)?

PS - Current sorting (non-numeric) is done using this function.

答:
I suggest to upgrade the used library a bit for using it with numerical values.

```<code>var x = is_numeric ? +a[columns[index]] : a[columns[index]].toLowerCase(); // <-- this line
var y = is_numeric ? +b[columns[index]] : b[columns[index]].toLowerCase(); // <-- this line
//                   ^ add this unary plus to get a numerical value istead of a string
</code>```

var helper = {
    arr: {
        /**
    * Function to sort multidimensional array
    *
    * param {array} [arr] Source array
    * param {array} [columns] List of columns to sort
    * param {array} [order_by] List of directions (ASC, DESC)
    * returns {array}
    */
        multisort: function (arr, columns, order_by) {
            if (typeof columns == 'undefined') {
                columns = []
                for (x = 0; x < arr[0].length; x++) {
                    columns.push(x);
                }
            }

            if (typeof order_by == 'undefined') {
                order_by = []
                for (x = 0; x < arr[0].length; x++) {
                    order_by.push('ASC');
                }
            }

            function multisort_recursive(a, b, columns, order_by, index) {
                var direction = order_by[index] == 'DESC' ? 1 : 0;

                var is_numeric = !isNaN(a[columns[index]] - b[columns[index]]);

                var x = is_numeric ? +a[columns[index]] : a[columns[index]].toLowerCase(); // add plus
                var y = is_numeric ? +b[columns[index]] : b[columns[index]].toLowerCase(); // add plus
                //                   ^ add this unary plus to get a numerical value istead of a string

                if (!is_numeric) {
                    x = helper.string.to_ascii(a[columns[index]].toLowerCase(), -1),
                    y = helper.string.to_ascii(b[columns[index]].toLowerCase(), -1);
                }

                if (x < y) {
                    return direction == 0 ? -1 : 1;
                }

                if (x == y) {
                    return columns.length - 1 > index ? multisort_recursive(a, b, columns, order_by, index + 1) : 0;
                }

                return direction == 0 ? 1 : -1;
            }

            return arr.sort(function (a, b) {
                return multisort_recursive(a, b, columns, order_by, 0);
            });
        }
    }
};

var array = [{ reference: "8926", name: "xyz1", id_product: "78" }, { reference: "11588", name: "xyz2", id_product: "21" }, { reference: "119", name: "xyz3", id_product: "135" }];

console.log(helper.arr.multisort(array, ['reference'], ['ASC']));
console.log(helper.arr.multisort(array, ['reference'], ['DESC']));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have a JS array in following structure:

Array(
    [0] => Array(
        reference : "8926"
        name : "xyz1"
        id_product : "78"
    )
    [1] => Array(
        reference : "11588"
        name : "xyz2"
        id_product : "21"
    )
    [2] => Array(
        reference : "119"
        name : "xyz3"
        id_product : "135"
    )
)

I needed to sort this array using the reference key, I have done it using multisort function;

But the problem is : even though reference is numeric but in the array structure it is defined as string and hence instead of sorting like:
119, 8926, 11588 it is sorting it like 11588 119 8926, i.e., like string.

I cannot re-structure the array because I receive it through an API, is there anyway to sort it numerically without having to recreate it in numeric data type separately (because I have to pass the array forward in same format & hence double-conversion will make the script hectic)?

PS - Current sorting (non-numeric) is done using this function.

Body:
I suggest to upgrade the used library a bit for using it with numerical values.

var x = is_numeric ? +a[columns[index]] : a[columns[index]].toLowerCase(); // <-- this line
var y = is_numeric ? +b[columns[index]] : b[columns[index]].toLowerCase(); // <-- this line
//                   ^ add this unary plus to get a numerical value istead of a string

var helper = {
    arr: {
        /**
    * Function to sort multidimensional array
    *
    * param {array} [arr] Source array
    * param {array} [columns] List of columns to sort
    * param {array} [order_by] List of directions (ASC, DESC)
    * returns {array}
    */
        multisort: function (arr, columns, order_by) {
            if (typeof columns == 'undefined') {
                columns = []
                for (x = 0; x < arr[0].length; x++) {
                    columns.push(x);
                }
            }

            if (typeof order_by == 'undefined') {
                order_by = []
                for (x = 0; x < arr[0].length; x++) {
                    order_by.push('ASC');
                }
            }

            function multisort_recursive(a, b, columns, order_by, index) {
                var direction = order_by[index] == 'DESC' ? 1 : 0;

                var is_numeric = !isNaN(a[columns[index]] - b[columns[index]]);

                var x = is_numeric ? +a[columns[index]] : a[columns[index]].toLowerCase(); // add plus
                var y = is_numeric ? +b[columns[index]] : b[columns[index]].toLowerCase(); // add plus
                //                   ^ add this unary plus to get a numerical value istead of a string

                if (!is_numeric) {
                    x = helper.string.to_ascii(a[columns[index]].toLowerCase(), -1),
                    y = helper.string.to_ascii(b[columns[index]].toLowerCase(), -1);
                }

                if (x < y) {
                    return direction == 0 ? -1 : 1;
                }

                if (x == y) {
                    return columns.length - 1 > index ? multisort_recursive(a, b, columns, order_by, index + 1) : 0;
                }

                return direction == 0 ? 1 : -1;
            }

            return arr.sort(function (a, b) {
                return multisort_recursive(a, b, columns, order_by, 0);
            });
        }
    }
};

var array = [{ reference: "8926", name: "xyz1", id_product: "78" }, { reference: "11588", name: "xyz2", id_product: "21" }, { reference: "119", name: "xyz3", id_product: "135" }];

console.log(helper.arr.multisort(array, ['reference'], ['ASC']));
console.log(helper.arr.multisort(array, ['reference'], ['DESC']));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
C# Classes to List => Loop => Print Out
Hey guys I recently started learning C# using microsoft .Net Tutorials.

I'm stuck at "Classes and Objects" Lesson.
At the end of the each lesson we have a little "homework" to do.
I need to write a program that prints out addresses for people and companies using three different classes (Person, Copmany, Address). I need to add them to collection and loop through, printing out the address for each company or person.

Here is the LINK (at the end of the page there is an example how the program should look like.

I'm not really sure how am I suppose to achieve this. Can someone please help me understand. This is what I come so far:

```<code>public class Address
{
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }

public override string ToString()
{
    return $"{StreetAddress}, {City}, {PostalCode}, {Country}";
}
public Address()
{
    StreetAddress = "Main123";
    City = "SomeTown";
    State = "OH";
    PostalCode = "12345";
    Country = "United States";
}
}

public class Person : Master
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address ShippingAddress { get; set; }

public Person(string firstName, string lastName)
{
    FirstName = firstName;
    LastName = lastName;
    ShippingAddress = new Address();
}
public override string ToString()
{
    return $"{FirstName} {LastName} {ShippingAddress}\n";
}
}

public class Company : Master
{
public string Name { get; set; }
public Address ShippingAddress { get; set; }

public Company(string name)
{
    Name = name;
    ShippingAddress = new Address();
}
public override string ToString()
{
    return $"{Name} {ShippingAddress}\n";
}
}

public class Master
{
public static List<Master> data = new List<Master>();
public static void Coll(Master master)
{
    data.Add(master);
    data.ForEach(Console.WriteLine);
}
}

class MainClass
{
public static void Main(string[] args)
{
    Person John = new Person("John", "Smith");
    Master.Coll(John);
}
}
</code>```

答:
This is fairly straight forward. You can do it using interfaces or polymorphism.

You need put objects into collection, and iterate through all of them.

```<code>entityList = new List<IPrintable>();
foreach(var entity in entityList)
{
    entity.PrintAddress();
}
</code>```

To achieve this, you need to use common interface for both classes;

```<code>internal interface IPrintable
{
    void PrintAddress();
}
</code>```

You need to implement this interface in both classes.

```<code>public class Person : IPrintable
{
    public void Print()
    {
        Console.WriteLine("Person's address is {0}", ShippingAddress.ToString());
    }
}

public class Company : IPrintable
{
    public void Print()
    {
        Console.WriteLine("Company's is {0}", ShippingAddress.ToString());
    }
}

public class Address
{
    public string ToString()
    {
        return string.Format(" Street: {0}, {1}, {2}, {3}, post code{4}, {5}", StreetAddress, City, State, PostalCode, Country);
    }
}
</code>```

Instead of having common interface you can make abstract base class, which will hold ShippingAddress field and have virtual method Print() without implementation. Then this base class will be type you use in List class
   var entitylist = newList();

```<code>public abstract class ShippableEntity
{
    private Address _Address;

    private ShippableEntity(Address address)
    {
        _Address = address;
    }

    public abstract void Print();

    public Address ShippingAddress { get { return _Address; } }
}
</code>```

Then you inherit this class in Person and Company and implement Print method in concrete classes.
Then you can do:
    entitylist.Add(new Person(....));
    entitylist.Add(new Company(....));

and do the same thing with foreach as with interface.

You need to call base class constructor!

```<code>public class Person : ShippableEntity
{
     public Person(Address address)
             : base(adress)
     {
     }
}
</code>```

I hope this helps.

Title: C# Classes to List => Loop => Print Out

Body:
Hey guys I recently started learning C# using microsoft .Net Tutorials.

I'm stuck at "Classes and Objects" Lesson.
At the end of the each lesson we have a little "homework" to do.
I need to write a program that prints out addresses for people and companies using three different classes (Person, Copmany, Address). I need to add them to collection and loop through, printing out the address for each company or person.

Here is the LINK (at the end of the page there is an example how the program should look like.

I'm not really sure how am I suppose to achieve this. Can someone please help me understand. This is what I come so far:

public class Address
{
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }

public override string ToString()
{
    return $"{StreetAddress}, {City}, {PostalCode}, {Country}";
}
public Address()
{
    StreetAddress = "Main123";
    City = "SomeTown";
    State = "OH";
    PostalCode = "12345";
    Country = "United States";
}
}

public class Person : Master
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address ShippingAddress { get; set; }

public Person(string firstName, string lastName)
{
    FirstName = firstName;
    LastName = lastName;
    ShippingAddress = new Address();
}
public override string ToString()
{
    return $"{FirstName} {LastName} {ShippingAddress}\n";
}
}

public class Company : Master
{
public string Name { get; set; }
public Address ShippingAddress { get; set; }

public Company(string name)
{
    Name = name;
    ShippingAddress = new Address();
}
public override string ToString()
{
    return $"{Name} {ShippingAddress}\n";
}
}

public class Master
{
public static List<Master> data = new List<Master>();
public static void Coll(Master master)
{
    data.Add(master);
    data.ForEach(Console.WriteLine);
}
}

class MainClass
{
public static void Main(string[] args)
{
    Person John = new Person("John", "Smith");
    Master.Coll(John);
}
}

Body:
This is fairly straight forward. You can do it using interfaces or polymorphism.

You need put objects into collection, and iterate through all of them.

entityList = new List<IPrintable>();
foreach(var entity in entityList)
{
    entity.PrintAddress();
}

To achieve this, you need to use common interface for both classes;

internal interface IPrintable
{
    void PrintAddress();
}

You need to implement this interface in both classes.

public class Person : IPrintable
{
    public void Print()
    {
        Console.WriteLine("Person's address is {0}", ShippingAddress.ToString());
    }
}

public class Company : IPrintable
{
    public void Print()
    {
        Console.WriteLine("Company's is {0}", ShippingAddress.ToString());
    }
}

public class Address
{
    public string ToString()
    {
        return string.Format(" Street: {0}, {1}, {2}, {3}, post code{4}, {5}", StreetAddress, City, State, PostalCode, Country);
    }
}

Instead of having common interface you can make abstract base class, which will hold ShippingAddress field and have virtual method Print() without implementation. Then this base class will be type you use in List class
   var entitylist = newList();

public abstract class ShippableEntity
{
    private Address _Address;

    private ShippableEntity(Address address)
    {
        _Address = address;
    }

    public abstract void Print();

    public Address ShippingAddress { get { return _Address; } }
}

Then you inherit this class in Person and Company and implement Print method in concrete classes.
Then you can do:
    entitylist.Add(new Person(....));
    entitylist.Add(new Company(....));

and do the same thing with foreach as with interface.

You need to call base class constructor!

public class Person : ShippableEntity
{
     public Person(Address address)
             : base(adress)
     {
     }
}

I hope this helps.


问:
Direct3D over Remote Desktop
How can I get Direct3D to work over a Remote Desktop connection? I am using Windows XP Professional.</p>

答: It works for me if I start the 3D program first in the local machine, and I later get the session using remote desktop.

OwnerDisplayName: Vulcan Eager

Title: Direct3D over Remote Desktop


问:
Does AWS support weighted load balancing?
Does AWS natively support weighted load balancing?

From what I see, ELB does only support round-robin load balancing (without any configurable weights). I have not found reliable documentation on it, though.

The easiest thing that I can think of is to put a load balancer like Nginx in front of it, for example:

```<code>upstream backend  {
  server backend1.example.com weight=1;
  server backend2.example.com weight=2;
  server backend3.example.com weight=4;
}
</code>```

Here, out of seven requests, one will go to backend1, two to backend2, and four to backend4.

It will work, but it also means you have to setup a server with Nginx just for that. If AWS would directly support weighted load balancing that would be far easier to setup.

答:
If you are using AWS Route 53 as DNS service, you can configure the weight-age on DNS record.

DNS weight-age refer 2.2

Amazon Route 53 support Weighted Round Robin. Weighted Round Robin
  allows you to assign weights to resource record sets in order to
  specify the frequency with which different responses are served. You
  may want to use this capability to do A/B testing, sending a small
  portion of traffic to a server on which you’ve made a software change.
  For instance, suppose you have two record sets associated with one DNS
  name—one with weight 3 and one with weight 1. In this case, 75% of the
  time Route 53 will return the record set with weight 3 and 25% of the
  time Route 53 will return the record set with weight 1. Weights can be
  any number between 0 and 255.

Body:
Does AWS natively support weighted load balancing?

From what I see, ELB does only support round-robin load balancing (without any configurable weights). I have not found reliable documentation on it, though.

The easiest thing that I can think of is to put a load balancer like Nginx in front of it, for example:

upstream backend  {
  server backend1.example.com weight=1;
  server backend2.example.com weight=2;
  server backend3.example.com weight=4;
}

Here, out of seven requests, one will go to backend1, two to backend2, and four to backend4.

It will work, but it also means you have to setup a server with Nginx just for that. If AWS would directly support weighted load balancing that would be far easier to setup.


问:
Mysql Procedure Syntax error on Update
```<code>DELIMITER //

DROP PROCEDURE IF EXISTS pad_fato_to_tad_fato//

CREATE PROCEDURE pad_fato_to_tad_fato(IN IDFATO BIGINT, IN UCI BIGINT)

BEGIN
  INSERT INTO tad_fato (FAT_UCI, FAT_DESCRICAO,
                        FAT_DATA_CIENCIA_AUTORIDADE,
                        FAT_CADASTRANTE, FAT_DATA_CAD)
   SELECT FAT_UCI, FAT_DESCRICAO, FAT_DATA_CIENCIA_AUTORIDADE,
      FAT_CADASTRANTE, FAT_DATA_CAD
   FROM pad_fato WHERE (FAT_ID = IDFATO);
END//

BEGIN
  UPDATE tad_termo_de_ajustamento SET TAD_STATUS_ID="2" WHERE (TAD_FK_PRE_UCI = UCI);
END//

DELIMITER ;
</code>```

Error (12,1): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near UPDATE tad_termo_de_ajustamento SET TAD_STATUS_ID="2" WHERE (TAD_FK_PRE_UCI=UCI) at line 2

答:
You have double "END" word after each query.
And not pretty formatted code :)</p>

```<code>DELIMITER //

DROP PROCEDURE IF EXISTS pad_fato_to_tad_fato//

CREATE PROCEDURE pad_fato_to_tad_fato(IN IDFATO BIGINT, IN UCI BIGINT)

BEGIN
    INSERT INTO tad_fato (
        FAT_UCI,FAT_DESCRICAO,
        FAT_DATA_CIENCIA_AUTORIDADE,
        FAT_CADASTRANTE,FAT_DATA_CAD
    )
    SELECT
        FAT_UCI,
        FAT_DESCRICAO,
        FAT_DATA_CIENCIA_AUTORIDADE,
        FAT_CADASTRANTE,
        FAT_DATA_CAD
    FROM pad_fato
    WHERE (FAT_ID=IDFATO);

    UPDATE tad_termo_de_ajustamento
    SET
        TAD_STATUS_ID="2"
    WHERE (TAD_FK_PRE_UCI=UCI);
END//

DELIMITER ;
</code>```

Title: Mysql Procedure Syntax error on Update

Body:
DELIMITER //

DROP PROCEDURE IF EXISTS pad_fato_to_tad_fato//

CREATE PROCEDURE pad_fato_to_tad_fato(IN IDFATO BIGINT, IN UCI BIGINT)

BEGIN
  INSERT INTO tad_fato (FAT_UCI, FAT_DESCRICAO,
                        FAT_DATA_CIENCIA_AUTORIDADE,
                        FAT_CADASTRANTE, FAT_DATA_CAD)
   SELECT FAT_UCI, FAT_DESCRICAO, FAT_DATA_CIENCIA_AUTORIDADE,
      FAT_CADASTRANTE, FAT_DATA_CAD
   FROM pad_fato WHERE (FAT_ID = IDFATO);
END//

BEGIN
  UPDATE tad_termo_de_ajustamento SET TAD_STATUS_ID="2" WHERE (TAD_FK_PRE_UCI = UCI);
END//

DELIMITER ;

Error (12,1): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near UPDATE tad_termo_de_ajustamento SET TAD_STATUS_ID="2" WHERE (TAD_FK_PRE_UCI=UCI) at line 2

Body:
You have double "END" word after each query.
And not pretty formatted code :)

DELIMITER //

DROP PROCEDURE IF EXISTS pad_fato_to_tad_fato//

CREATE PROCEDURE pad_fato_to_tad_fato(IN IDFATO BIGINT, IN UCI BIGINT)

BEGIN
    INSERT INTO tad_fato (
        FAT_UCI,FAT_DESCRICAO,
        FAT_DATA_CIENCIA_AUTORIDADE,
        FAT_CADASTRANTE,FAT_DATA_CAD
    )
    SELECT
        FAT_UCI,
        FAT_DESCRICAO,
        FAT_DATA_CIENCIA_AUTORIDADE,
        FAT_CADASTRANTE,
        FAT_DATA_CAD
    FROM pad_fato
    WHERE (FAT_ID=IDFATO);

    UPDATE tad_termo_de_ajustamento
    SET
        TAD_STATUS_ID="2"
    WHERE (TAD_FK_PRE_UCI=UCI);
END//

DELIMITER ;


问:
MinimalModbus read_registry error
I am trying to read registry information from a modbus device using MinimalModbus. However, every time I attempt to read registry 40003 which has a value of 220 I receive this error:

```<code>raise ValueError('The slave is indicating an error. The response is: {!r}'.format(response))
ValueError: The slave is indicating an error. The response is: '\x01\x83\x02Àñ'
</code>```

I know there is a value in 40003 and I am following the communication documents for the device. Here is my code:

```<code>import minimalmodbus
import serial

gas = minimalmodbus.Instrument('COM5', 1)
gas.serial.baudrate = 9600
gas.serial.bytesize = 8
gas.serial.parity   = serial.PARITY_NONE
gas.serial.stopbits = 1
gas.serial.timeout  = 0.05
gas.mode = minimalmodbus.MODE_RTU

temp = gas.read_register(40003, 1)
print (float(temp))
</code>```

I have this problem for every registry and I cannot find information regarding Àñ.

答: The problem was the registry number 40003. I guess the modbus protocol doesn't require the full registry number, so I changed it to temp = gas.read_register(3, 1)

Title: MinimalModbus read_registry error

Body:
I am trying to read registry information from a modbus device using MinimalModbus. However, every time I attempt to read registry 40003 which has a value of 220 I receive this error:

raise ValueError('The slave is indicating an error. The response is: {!r}'.format(response))
ValueError: The slave is indicating an error. The response is: '\x01\x83\x02Àñ'

I know there is a value in 40003 and I am following the communication documents for the device. Here is my code:

import minimalmodbus
import serial

gas = minimalmodbus.Instrument('COM5', 1)
gas.serial.baudrate = 9600
gas.serial.bytesize = 8
gas.serial.parity   = serial.PARITY_NONE
gas.serial.stopbits = 1
gas.serial.timeout  = 0.05
gas.mode = minimalmodbus.MODE_RTU

temp = gas.read_register(40003, 1)
print (float(temp))

I have this problem for every registry and I cannot find information regarding Àñ.


问:
Python Text Game : Program improvement
I have the following code, which works. but I am struck with list dependency
which starts indexing with 0. That is,

When user Chooses, 1 it takes 0th element
When user Chooses, 2 it takes 1st element
When user Chooses, 3 it takes 2nd element.. I t goes on like this.

I wants to overcome this, but not with any hack like internally converting the given text=text-1. please help. with any other solution

```<code>import numpy as np
Ran=[np.random.randint(1,5)]
Val=Ran[0]
print(Val)
#Items
items=['1. pot plant','2. painting','3. vase','4. lampshade','5. shoe']
print ("\n")
#Intro Text
print ("Last night you went to sleep in the comfort of your own home.")
print ("Now, you find yourself locked in a room. You don't know how")
print ("you got there or what time it is. In the room you can see")
print ("\n")
print (len(items), "Things:")
for x in items:
    print (x)
print ("")
print ("The door is locked. Could there be a key somewhere?")
print ("Enter the corresponding number of thing which you \
would like to check..Yougot only 3 chances !! ")
k=0
while (k==0):
    Ins1 = int(input())
    if (Ins1 == Val):
        print("You're Lucky! Got the key in First instance ")
        break
    else:
        c=items[Ins1]
        print("Damn ! key is not available in ", c , "Try again..")
    Ins2 = int(input())
    if (Ins2 == Val):
        print("Got the key on your 2nd attempt")
        break
    else:
        c=items[Ins2]
        print("Bad luck ! Try again..not in ", c ,"your last attempt")
    Ins3 = int(input())
    if (Ins3 == Val):
        print("Finally you got the key")
        break
    else:
        c=items[Ins3]
        print("you're done. Die here :( Key not in ",c,)
        break
</code>```

答:
Resolved in comments:

```<code>Just put a dummy '' value at the beginning of items. – Paul McGuire

But the user will view the dummy value, as am printing the options to him. – Abdul Salam

Just start at 1 then: for x in items[1:]: print(x) – Paul McGuire

Thanks Paul ! It works Fine :)
</code>```

Title: Python Text Game : Program improvement

Body:
I have the following code, which works. but I am struck with list dependency
which starts indexing with 0. That is,

When user Chooses, 1 it takes 0th element
When user Chooses, 2 it takes 1st element
When user Chooses, 3 it takes 2nd element.. I t goes on like this.

I wants to overcome this, but not with any hack like internally converting the given text=text-1. please help. with any other solution

import numpy as np
Ran=[np.random.randint(1,5)]
Val=Ran[0]
print(Val)
#Items
items=['1. pot plant','2. painting','3. vase','4. lampshade','5. shoe']
print ("\n")
#Intro Text
print ("Last night you went to sleep in the comfort of your own home.")
print ("Now, you find yourself locked in a room. You don't know how")
print ("you got there or what time it is. In the room you can see")
print ("\n")
print (len(items), "Things:")
for x in items:
    print (x)
print ("")
print ("The door is locked. Could there be a key somewhere?")
print ("Enter the corresponding number of thing which you \
would like to check..Yougot only 3 chances !! ")
k=0
while (k==0):
    Ins1 = int(input())
    if (Ins1 == Val):
        print("You're Lucky! Got the key in First instance ")
        break
    else:
        c=items[Ins1]
        print("Damn ! key is not available in ", c , "Try again..")
    Ins2 = int(input())
    if (Ins2 == Val):
        print("Got the key on your 2nd attempt")
        break
    else:
        c=items[Ins2]
        print("Bad luck ! Try again..not in ", c ,"your last attempt")
    Ins3 = int(input())
    if (Ins3 == Val):
        print("Finally you got the key")
        break
    else:
        c=items[Ins3]
        print("you're done. Die here :( Key not in ",c,)
        break

Body:
Resolved in comments:

Just put a dummy '' value at the beginning of items. – Paul McGuire

But the user will view the dummy value, as am printing the options to him. – Abdul Salam

Just start at 1 then: for x in items[1:]: print(x) – Paul McGuire

Thanks Paul ! It works Fine :)


问:
Find strings that start and end with certain characters
I'm working on a text-mining project with data from twitter. In my data frame, many words are converted into Unicode characters, e.g.

I want to collect every converted words like above and put them into 1 large string so I can deal with them separately.

Is there any way I can find all the strings that start with <U+ and end with > using R?

答:
Your request is a bit imprecise, so I'm taking the liberty to make a few assumptions on how you want the output.</p>

```<code>text <- "Words <Q+0E2B><U+0E2B2>, 1 < 2, <p>
         <U+0E2B><U+0E25><U+0E07><U+0E1E> </p> some more words"

regmatches(text, gregexpr("<U\\+[0-9A-Z]{4}>", text))
# "<U+0E2B>" "<U+0E25>" "<U+0E07>" "<U+0E1E>"
</code>```

Body:
Your request is a bit imprecise, so I'm taking the liberty to make a few assumptions on how you want the output.

text <- "Words <Q+0E2B><U+0E2B2>, 1 < 2, <p>
         <U+0E2B><U+0E25><U+0E07><U+0E1E> </p> some more words"

regmatches(text, gregexpr("<U\\+[0-9A-Z]{4}>", text))
# "<U+0E2B>" "<U+0E25>" "<U+0E07>" "<U+0E1E>"


问:
Disable ionic console colors
The ionic shell tool uses colours by default which makes the output unreadable in a black-on-white console (KDE konsole on Ubuntu).

Is there an option to disable the colours, i.e. use the default text colour only?

答:
If you look into the ionic sh you will see that they Using Node.js chalk.

you can start your command with parameters or set a global environment variable:

https://github.com/chalk/supports-color#info

Title: Disable ionic console colors


问:
which data structure should I use in java to store duplicate values?
Which is the best data structure to store duplicate values in java? And how easy is to retrieve values from it!?

thanks
EDIT #1 I am reading contents from 1000 files, and I want to put each files content as tokens in some data structure. I used Hashtable but i am not able to view many words when I am doing that. thats why I want a data structure which can store the duplicate values.

答: Use Arrays, to get value use index (I know its incomplete answer, but so is the question)</p>


问:
Laravel loging can't find a route
I am creating Laravel 5 application.

I stuck with loggig problem.

Here are my routes.php

```<code><?php
Route::get('/', function () {
    return view('welcome');
});

// route to show the login form
Route::get('/login', array('uses' => 'HandleController@login'));
// route to process the form
Route::post('/login', array('uses' => 'HandleController@handleLogin'));
</code>```

My HandleContrroler and it's methodes

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests;

class HandleController extends Controller
{
    public function login()
    {
      return view('login');
    }

    public function handleLogin(Request $request)
    {
      $this->validate($request, User::$login_validation_rules);
      $data = $request->only('email', 'password');
      if(\Auth::attempt($data)){
          return redirect()->intended('home');
      }

      return back()->withInput()->withErrors(['email' => 'Username or password is invalid']);
    }

    public function logout()
    {
      \Auth::logout();
      return redirect()->route('login');
    }
}
</code>```

I don't there should be a problem with my view file.
When I am going to the projcet/directory/login in my web browser I am getting NotFoundHttpException. Screenshot below.

答:
After logout you are redirecting to route with name login, which doesn't exist.

SOLUTION:
In the routes.php add a name to your login route.

```<code>// route to show the login form
Route::get('/login', array('uses' => 'HandleController@login'))->name('login');
</code>```

Title: Laravel loging can't find a route

Body:
I am creating Laravel 5 application.

I stuck with loggig problem.

Here are my routes.php

<?php
Route::get('/', function () {
    return view('welcome');
});

// route to show the login form
Route::get('/login', array('uses' => 'HandleController@login'));
// route to process the form
Route::post('/login', array('uses' => 'HandleController@handleLogin'));

My HandleContrroler and it's methodes

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests;

class HandleController extends Controller
{
    public function login()
    {
      return view('login');
    }

    public function handleLogin(Request $request)
    {
      $this->validate($request, User::$login_validation_rules);
      $data = $request->only('email', 'password');
      if(\Auth::attempt($data)){
          return redirect()->intended('home');
      }

      return back()->withInput()->withErrors(['email' => 'Username or password is invalid']);
    }

    public function logout()
    {
      \Auth::logout();
      return redirect()->route('login');
    }
}

I don't there should be a problem with my view file.
When I am going to the projcet/directory/login in my web browser I am getting NotFoundHttpException. Screenshot below.

Body:
After logout you are redirecting to route with name login, which doesn't exist.

SOLUTION:
In the routes.php add a name to your login route.

// route to show the login form
Route::get('/login', array('uses' => 'HandleController@login'))->name('login');


问:
How to group similar Laravel routes using the same controller?
I want to pretty-up my routes, ie, I have such entries:

```<code>// DataTable
Route::get('dt/reservations/{room_id]', 'DataTablesController@reservations')->where(['room_id', '[0-9]+']);
Route::get('dt/rooms/{area_id]', 'DataTablesController@rooms')->where(['area_id', '[0-9]+']);
Route::get('dt/departments', 'DataTablesController@departments');
Route::get('dt/addresses', 'DataTablesController@areas');
Route::get('dt/areas', 'DataTablesController@areas');
</code>```

I would like to make it more understandable. I can add prefix what would give me:

```<code>// DataTable
Route::group(['prefix' => 'dt'], function () {
    Route::get('reservations/{room_id]', 'DataTablesController@reservations')->where(['room_id', '[0-9]+']);
    Route::get('rooms/{area_id]', 'DataTablesController@rooms')->where(['area_id', '[0-9]+']);
    Route::get('departments', 'DataTablesController@departments');
    Route::get('addresses', 'DataTablesController@areas');
    Route::get('areas', 'DataTablesController@areas');
});
</code>```

But can I somehow make the rest too? The route name and method name will always be the same.
Is it possible to make something like:

```<code>// DataTable
Route::group(['prefix' => 'dt'], function () {
    Controller => DataTablesController,
    Methods => [
        'reservations',
        'rooms',
        'departments',
        'addresses',
        'areas'
    ];
});
</code>```

答:
Although a very good feature. But it can't be done in Laravel

All your routes must be explicit, Laravel won't/can't assume that you
  are using same controller for all the routes.
  So you will have to define all the routes explicitly.

Only Resource Controllers can have implicit routing in Laravel

Take a look here....

Route use the same controller

Body:
I want to pretty-up my routes, ie, I have such entries:

// DataTable
Route::get('dt/reservations/{room_id]', 'DataTablesController@reservations')->where(['room_id', '[0-9]+']);
Route::get('dt/rooms/{area_id]', 'DataTablesController@rooms')->where(['area_id', '[0-9]+']);
Route::get('dt/departments', 'DataTablesController@departments');
Route::get('dt/addresses', 'DataTablesController@areas');
Route::get('dt/areas', 'DataTablesController@areas');

I would like to make it more understandable. I can add prefix what would give me:

// DataTable
Route::group(['prefix' => 'dt'], function () {
    Route::get('reservations/{room_id]', 'DataTablesController@reservations')->where(['room_id', '[0-9]+']);
    Route::get('rooms/{area_id]', 'DataTablesController@rooms')->where(['area_id', '[0-9]+']);
    Route::get('departments', 'DataTablesController@departments');
    Route::get('addresses', 'DataTablesController@areas');
    Route::get('areas', 'DataTablesController@areas');
});

But can I somehow make the rest too? The route name and method name will always be the same.
Is it possible to make something like:

// DataTable
Route::group(['prefix' => 'dt'], function () {
    Controller => DataTablesController,
    Methods => [
        'reservations',
        'rooms',
        'departments',
        'addresses',
        'areas'
    ];
});


问:
Issue configuring Redmon port
I'm using Windows 10.  I have the redirected printer installed just fine.  But when I go to configure the port, after selecting my redirection program and putting in my arguments, when I click OK and error box pops up that says, "An error occurred during port configuration.  Incorrect function".

I've uninstalled and reinstalled Redmon.  I've deleted the ports and added new ones.  But still I keep getting this error.  I have admin control and all permissions.

Thanks.

答: You can configure the port using the Print Management program, rather than the usual Printers & Scanners app, I'm not sure why though :)</p>

Title: Issue configuring Redmon port


问:
How to send FCM Push Notifications to multiple topics
I am using php server to send FCM push notifications. I want to know how I can send push notifications to multiple topics at the same time.

Here is my code.

```<code>function sendPush($topic,$msg){
$API_ACCESS_KEY = '...';
$msg = array
(
    'msg' => $msg
);

$fields = array('to' => '/topics/' . $topic, 'priority' => 'high', 'data' => $msg);
$headers = array
(
'Authorization: key=' . $API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$pushResult = curl_exec($ch);
curl_close($ch);
}
</code>```

答:
You use the condition key to send to multiple topics.

For example:

```<code>{
  "condition": "'dogs' in topics || 'cats' in topics",
  "priority" : "high",
  "notification" : {
    "body" : "This is a Firebase Cloud Messaging Topic Message!",
    "title" : "FCM Message",
  }
}
</code>```

This would send the message to devices subscribed to topics "dogs" or "cats".

Relevant quote from FCM docs:

To send to combinations of multiple topics, the app server sets the condition key to a boolean condition that specifies the target topics.

Note that you are limited to 2 boolean conditions, which means you can send a single message to at most 3 topics.

Update: Now you can include 5 topics.

You can include up to five topics in your conditional expression, and
  parentheses are supported. Supported operators: &&, ||, !. Note the
  usage for !:

Read the documentation at:
https://firebase.google.com/docs/cloud-messaging/send-message

Body:
I am using php server to send FCM push notifications. I want to know how I can send push notifications to multiple topics at the same time.

Here is my code.

function sendPush($topic,$msg){
$API_ACCESS_KEY = '...';
$msg = array
(
    'msg' => $msg
);

$fields = array('to' => '/topics/' . $topic, 'priority' => 'high', 'data' => $msg);
$headers = array
(
'Authorization: key=' . $API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$pushResult = curl_exec($ch);
curl_close($ch);
}

Body:
You use the condition key to send to multiple topics.

For example:

{
  "condition": "'dogs' in topics || 'cats' in topics",
  "priority" : "high",
  "notification" : {
    "body" : "This is a Firebase Cloud Messaging Topic Message!",
    "title" : "FCM Message",
  }
}

This would send the message to devices subscribed to topics "dogs" or "cats".

Relevant quote from FCM docs:

To send to combinations of multiple topics, the app server sets the condition key to a boolean condition that specifies the target topics.

Note that you are limited to 2 boolean conditions, which means you can send a single message to at most 3 topics.

Update: Now you can include 5 topics.

You can include up to five topics in your conditional expression, and
  parentheses are supported. Supported operators: &&, ||, !. Note the
  usage for !:

Read the documentation at:
https://firebase.google.com/docs/cloud-messaging/send-message

ContentLicense: CC BY-SA 4.0


问:
SQL Server (T-SQL): Avoid call scalar function multiple times
I have a stored procedure which does a SELECT to return some rows. Within the SELECT, I need to check a condition in order to return the correct value for some columns. This condition consists on a scalar function. All times scalar function is called with the same parameter for the row being processed, see below:

```<code>SELECT
    Id,
    Name,
    Surname,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 10
        ELSE 99
    END as Factor1,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 15
        ELSE -1
    END as Factor2,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 30
        ELSE 70
    END as Factor3
FROM
    Employees
WHERE
    DepartmentId = 100
</code>```

I am worried about performance, I mean, I do not like to call scalar function dbo.GetNumTravels multiples times, so how to avoid this and only call it once and then used it all the times I need it?

答:
I am not sure about performances (anyway, do your tests considering other answers too), but I would like to test this.  I tried to reduce use of function and use of CASE too.  Pls let me know</p>

```<code>SELECT A.*
    , 10*F0+99*~F0 AS FACTOR1
    , 15*F0-1*~F0 AS FACTOR2
    , 30*F0+70*~F0 AS FACTOR3
FROM (
    SELECT
     Id,
     Name,
     Surname,
    CAST(CASE WHEN (dbo.GetNumTravels(Id) >= 50) THEN  1  ELSE 0 END AS BIT) AS F0
    FROM Employees
    WHERE DepartmentId = 100
     ) A
</code>```

Body:
I have a stored procedure which does a SELECT to return some rows. Within the SELECT, I need to check a condition in order to return the correct value for some columns. This condition consists on a scalar function. All times scalar function is called with the same parameter for the row being processed, see below:

SELECT
    Id,
    Name,
    Surname,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 10
        ELSE 99
    END as Factor1,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 15
        ELSE -1
    END as Factor2,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 30
        ELSE 70
    END as Factor3
FROM
    Employees
WHERE
    DepartmentId = 100

I am worried about performance, I mean, I do not like to call scalar function dbo.GetNumTravels multiples times, so how to avoid this and only call it once and then used it all the times I need it?

Body:
I am not sure about performances (anyway, do your tests considering other answers too), but I would like to test this.  I tried to reduce use of function and use of CASE too.  Pls let me know

SELECT A.*
    , 10*F0+99*~F0 AS FACTOR1
    , 15*F0-1*~F0 AS FACTOR2
    , 30*F0+70*~F0 AS FACTOR3
FROM (
    SELECT
     Id,
     Name,
     Surname,
    CAST(CASE WHEN (dbo.GetNumTravels(Id) >= 50) THEN  1  ELSE 0 END AS BIT) AS F0
    FROM Employees
    WHERE DepartmentId = 100
     ) A