小编und*_*dog的帖子

管理数据库中的产品计数

对不起,如果这个问题可能看起来很幼稚,但我遇到过需要管理电子商务商店数据库中产品数量的情况.

有一个带有整数变量的Product类,productCount它表示数据库中可供该站点用户看到的可用产品数.现在这个类可以被多个线程访问,或者可以说电子商务站点的几个用户.每个人都在添加或删除产品到他的购物车.

正在使用的ORM框架是休眠

示例代码

@Entity
@Table
class Product{
   @Column
   private int productCount;

   public void addProductToCart(){
     // decrements the product count by 1 & updates the database
   }

   public void removeTheProductFromTheCart(){
    // increments the product count by 1 & updates the database
   }
Run Code Online (Sandbox Code Playgroud)

从代码中可以清楚地看出,我需要对数据库中的产品计数进行并发检查,以防止丢失更新.

此外,如果多个用户尝试在数据库中仅添加单个左侧产品.应该将产品添加到哪个用户的购物车?

我对此做了一点研究

我找到的可能方法是

  1. 为Product创建单例类.这将确保整个应用程序中只有一个产品实例可用.

  2. 同步addProductToCart& removeTheProductFromTheCart方法.这将只允许一个线程更新产品计数并一次更新数据库.

  3. 使用数据库并发控制应用一些db事务隔离级别,乐观/悲观锁定productCount.我使用mysql的默认隔离级别是REPEATABLE_READ.

处理这个问题的最佳方法是什么?

java database concurrency multithreading thread-safety

19
推荐指数
2
解决办法
1778
查看次数

用于弹性搜索的远程GUI客户端

我在网上搜索得足够多,但没有找到解决方案.

是否有像Oracle SQL Developer一样的Elastic Search服务器的远程GUI客户端,以便查看远程弹性数据库的模式和其他详细信息.

目前我正在使用弹性头插件

在此输入图像描述

它不允许我连接到远程弹性群集.仅当弹性服务器托管在同一台计算机中时,它才有效.我还将以下条目添加到elastic.yml文件中,但不起作用.说no connection to the remote host.

#http.cors.enable: true
#http.cors.allow-origin: "remotehosturl:9200"
Run Code Online (Sandbox Code Playgroud)

elasticsearch elasticsearch-plugin

12
推荐指数
2
解决办法
4万
查看次数

Cloud Foundry和Pivotal Web Services之间的区别

我在维基百科上读到云代工开源软件可供任何人使用,而Pivotal Web Services是Pivotal的商业产品.

我在互联网上搜索了很多,但没有找到任何云代工厂开源软件实现示例.一切都是Pivotal产品,提供2个月的免费试用服务.

那么有谁能告诉我什么是云代工开源软件?云代工OSS和Pivotal CF的区别究竟是什么?

cloud-foundry

11
推荐指数
2
解决办法
9033
查看次数

HackerRank上两个堆栈游戏的正确算法

我刚刚在HackerRank上尝试了基于堆栈的问题

https://www.hackerrank.com/challenges/game-of-two-stacks

Alexa有两个非负整数堆栈,堆栈A和堆栈B,其中索引0表示堆栈的顶部.Alexa挑战Nick玩以下游戏:

在每次移动中,Nick都可以从堆栈A或B堆栈的顶部删除一个整数.

Nick保持他从两个堆栈中移除的整数的运行总和.

如果在任何时候,他的跑动总和大于游戏开始时给出的某个整数X,尼克就会被取消参赛资格.

尼克的最终得分是他从两个筹码中删除的整数总数.

在每场比赛中找到尼克可以达到的最大可能分数(即,他可以移除但不被取消资格的最大整数数)并将其打印在新线上.

对于每个游戏,在新线上打印一个整数,表示尼克可以在不被取消资格的情况下获得的最大可能分数.

Sample Input 0

1 -> Number of games
10 -> sum should not exceed 10 
4 2 4 6 1  -> Stack A
2 1 8 5 -> Stack B

Sample Output 

4
Run Code Online (Sandbox Code Playgroud)

下面是我的代码我尝试了贪婪的方法,从堆栈顶部取最小元素并将其添加到总和中.对于某些测试用例,它可以正常工作,但是对于下面的输入则无法休息

1
67
19 9 8 13 1 7 18 0 19 19 10 5 15 19 0 0 16 12 5 10 - Stack A
11 17 1 18 14 12 9 18 14 3 4 13 …
Run Code Online (Sandbox Code Playgroud)

java algorithm stack data-structures

9
推荐指数
1
解决办法
4453
查看次数

在Hibernate中级联类型保存更新

我正在使用带有JPA注释的hibernate进行关系映射.我的代码中有三个实体User Group&User_Group

UserGroup正在建立ManyToMany关系.

User_Group是一个有点桥牌表,但有一些额外的领域.所以这是修改后的映射代码.

用户

@Entity
@Table(name = "USERS")
public class User {

@OneToMany(mappedBy = "user")
private Set<UserGroup> userGroups
}
Run Code Online (Sandbox Code Playgroud)

@Entity
@Table(name = "GROUPS")
public class Group {
@OneToMany(mappedBy = "group")
private Set<UserGroup> userGroups
}
Run Code Online (Sandbox Code Playgroud)

用户组

@Entity
@Table(name = "USERS_GROUPS")
public class UserGroup {

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "USER_ID")  
private User user;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "GROUP_ID")
private Group group;
}
Run Code Online (Sandbox Code Playgroud)

当我将用户和组对象设置为用户组并保存时.

User user = new …
Run Code Online (Sandbox Code Playgroud)

java hibernate

7
推荐指数
2
解决办法
1万
查看次数

使用广度优先搜索查找最短路径节点

在此输入图像描述

我正在上面的图表上运行广度优先搜索,以找到从中Node 0到达的最短路径Node 6.

我的代码

public List<Integer> shortestPathBFS(int startNode, int nodeToBeFound){
        boolean shortestPathFound = false;
        Queue<Integer> queue = new LinkedList<Integer>();
        Set<Integer> visitedNodes = new HashSet<Integer>();
        List<Integer> shortestPath = new ArrayList<Integer>();
        queue.add(startNode);
        shortestPath.add(startNode);

        while (!queue.isEmpty()) {
            int nextNode = queue.peek();
            shortestPathFound = (nextNode == nodeToBeFound) ? true : false;
            if(shortestPathFound)break;
            visitedNodes.add(nextNode);
            System.out.println(queue);
            Integer unvisitedNode = this.getUnvisitedNode(nextNode, visitedNodes);

            if (unvisitedNode != null) {
                    queue.add(unvisitedNode);
                    visitedNodes.add(unvisitedNode);
                    shortestPath.add(nextNode); //Adding the previous node of the visited node 
                    shortestPathFound = (unvisitedNode == nodeToBeFound) …
Run Code Online (Sandbox Code Playgroud)

java algorithm breadth-first-search data-structures

6
推荐指数
2
解决办法
1万
查看次数

大气框架Spring mvc集成

我正在尝试将Atmosphere框架与Spring MVC集成

此处给出的示例war文件 http://async-io.org/download.html不包含src文件夹中的.java文件.

我还浏览了其他集成示例 http://keaplogik.blogspot.com/2012/05/atmosphere-websockets-comet-with-spring.html

在阅读本文时,我遇到了与twitter连接的问题.

A.某处有一个更简单的例子吗?像一个问候世界的解释.

B.如何获取示例war文件的java文件?

我真的很感激任何帮助谢谢:)

java eclipse spring spring-mvc atmosphere

5
推荐指数
1
解决办法
6888
查看次数

java.lang.ClassCastException:org.springframework.security.core.userdetails.User无法强制转换为model.User

我在我的应用程序中使用Spring Security.我需要在我的应用程序的控制器中登录用户详细信息.

为此,我使用此代码

User loggedInUser = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Run Code Online (Sandbox Code Playgroud)

但是在运行此代码时,我得到了classcastexception

java.lang.ClassCastException: org.springframework.security.core.userdetails.User cannot be cast to model.User
Run Code Online (Sandbox Code Playgroud)

为了解决这个问题,我参考了这篇文章

最初我使用了CustomUserServiceDetails类

@Service("myUserDetailService")
@Transactional
public class CustomUserDetailsService implements UserDetailsService {

    private static final Logger logger = Logger.getLogger(CustomUserDetailsService.class);

    @Autowired
    private UserDAO userDAO;

    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException, DataAccessException {
        // returns the get(0) of the user list obtained from the db
        User domainUser = userDAO.getUser(name);
        logger.debug("User fetched from database in loadUserByUsername method " + domainUser);

        Set<Role> roles = domainUser.getRole();
        logger.debug("role of the user" + …
Run Code Online (Sandbox Code Playgroud)

java spring spring-security

5
推荐指数
2
解决办法
3万
查看次数

Spring 集成 pubsub 与 Spring amqp RabbitMQ pubsub

我正在开发一个 MicroBlog spring mvc 休眠应用程序。我需要实现像 twitter 这样的发布订阅功能。

我正在使用 RabbitMQ 与 Spring AMQP 抽象进行消息传递。

我在网上看到的任何地方都给出了pubsub 示例,涉及

弹簧集成

Spring AMQP & RabbitMQ

我对 Spring-Integration 进行了更多研究,发现即使不使用 RabbitMQ 也可以使用它实现发布订阅。

现在我的问题是

为什么我需要使用 Spring Integration 和 [Spring AMQP & RabbitMQ] 来实现发布订阅功能。为什么我不能只使用 Spring AMQP 和 Rabbit 来做到这一点?

Spring 集成是否提供任何附加功能?

我的 Spring AMQP 和 RabbitMQ 配置

<rabbit:connection-factory id="connectionFactory" virtual-host="/" host="localhost" 
username="guest" password="guest"/>

<rabbit:admin connection-factory="connectionFactory" />

<rabbit:queue name="UserPostpublishQueue" />

<fanout-exchange name="broadcastUserPosts" xmlns="http://www.springframework.org/schema/rabbit">
    <bindings>
        <binding queue="UserPostpublishQueue"/>
    </bindings>
</fanout-exchange>

<rabbit:template id="amqpTemplate" connection-factory="connectionFactory" exchange="broadcastUserPosts" 
queue="UserPostpublishQueue"/>

</beans>
Run Code Online (Sandbox Code Playgroud)

在我的控制器中测试代码

@Autowire
private AmqpTemplate …
Run Code Online (Sandbox Code Playgroud)

java spring spring-integration rabbitmq spring-amqp

5
推荐指数
1
解决办法
1950
查看次数

在迭代复杂对象时避免嵌套 for 循环

我的应用程序中有一个比赛表,其中包含已安排比赛的详细信息

在此输入图像描述

我有一张user桌子和user_match一张桥桌。

user_match下表指定了有关哪个用户关注哪场比赛以及支持哪支球队的信息。 在此输入图像描述

现在,在我的控制器方法中,我将返回今天的预定比赛,并同时检查登录用户是否遵循今天的预定比赛。

问题是我必须在流程复杂度 O(n^2) 中运行两个嵌套的 for 循环。首先,我迭代当前的匹配项,然后对于当前的每个匹配项,我迭代用户关注的所有匹配项并检查当前匹配项是否存在。我希望如果我能摆脱嵌套的 for 循环,是否有更好的方法来处理这个问题。

@RequestMapping(value="/getTodaysMatches", method=RequestMethod.GET, consumes = "application/json", produces = "application/json")
public @ResponseBody List<Match> getMatchesForCurrentDate(){
    logger.debug("inside /getTodaysMatches CricketController method");

    DateTime currentServerTimeStamp = CricketUtil.getServerDateTime();
    List<Match> currentDayMatchList = this.cricketService.fetchMatchesForInputDate(currentServerTimeStamp);
    CustomUserDetail myUserDetails = currentUserAccessor.getCurrentLoggedInUser();
    User loggedInUser = myUserDetails.getUser();
    List<UserMatchInfo> userMatchInfoList = this.cricketService.getUserMatchInfoByUserId(loggedInUser.getUserId());

    /*check if the logged in user already follows matches scheduled for today*/

    for(Match  todaysMatch : currentDayMatchList){
        for(UserMatchInfo tmpUserMatchInfo : userMatchInfoList){
            String teamFollowedByUser = tmpUserMatchInfo.getSupportingTeam();
            Match matchWhichUserFollows = tmpUserMatchInfo.getMatch(); …
Run Code Online (Sandbox Code Playgroud)

java performance

4
推荐指数
1
解决办法
8376
查看次数